2015-10-15 110 views
1

我曾經有一個自定義類的實例定義在app.xaml.cs中,所以我可以在我的應用程序的任何地方訪問它。我現在怎麼改變它以便在我的應用程序資源中創建我的課程實例。從代碼背後訪問XAML實例類

的App.xaml

<Application x:Class="Duplicate_Deleter.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:Duplicate_Deleter"> 
    <Application.Resources> 
     <local:runtimeObject x:Key="runtimeVariables" /> 
    </Application.Resources> 
</Application> 

App.xaml.cs 這是類。

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows; 

namespace Duplicate_Deleter 
    /// <summary> 
    /// Global values for use during application runtime 
    /// </summary> 
    public class runtimeObject 
    { 
     //Can the application be closed? 
     private bool _inProgress = false; 
     public bool inProgress 
     { 
      get { return _inProgress; } 
      set { _inProgress = value; } 
     } 

     //Selected folder to search in 
     private string _fromFolder = "testing string"; 
     public string fromFolder 
     { 
      get { return _fromFolder; } 
      set { _fromFolder = value; } 
     } 
    } 
} 

我現在的問題是,我需要能夠在我的代碼中在我的命令命名空間中訪問這個類的實例。您可以在下面看到其中一個命令,App.runtime用於實例在App.xaml.cs中時工作。

類> Commands.cs

public static void CloseWindow_CanExecute(object sender, 
          CanExecuteRoutedEventArgs e) 
     { 
      if (App.runtime.inProgress == true) 
      { 
       e.CanExecute = false; 
      } 
      else 
      { 
       e.CanExecute = true; 
      } 
     } 

我現在該如何從我的命令中引用我的類的實例?

回答

2

您可以在代碼中任何地方使用TryFindResource:

public static void CloseWindow_CanExecute(object sender, 
         CanExecuteRoutedEventArgs e) 
    { 
     // Find the resource, then cast it to a runtimeObject 
     var runtime = (runtimeObject)Application.Current.TryFindResource("runtimeVariables"); 

     if (runtime.InProgress == true) 
     { 
      e.CanExecute = false; 
     } 
     else 
     { 
      e.CanExecute = true; 
     } 
    } 

如果未找到該資源將返回null。您可以添加空檢查以避免InvalidCastException。

+0

這很奇怪,我收到「TryFindResource」的錯誤,錯誤:'TryFindResource'在當前上下文中不存在' –

+0

嗯,這很奇怪,那麼FindResource呢? – kskyriacou

+0

我想通了 - 這是因爲你在主窗口之外的課程中調用它。使用Application.Current.TryFindResource(..),更新我的答案 – kskyriacou