2012-10-24 43 views
1

我在XAML中聲明,像這樣的資源:FindResource在Window.Resources

<Window x:Class="Test.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Test" 
    Title="MainWindow" Height="350" Width="525" Name="form1"> 
    <Window.Resources> 
    <ObjectDataProvider x:Key="SingleRole" ObjectType="{x:Type local:SingleRole}" /> 
    </Window.Resources> 
... 
</Window> 

我試圖讓在代碼中對象的引用:

private void button1_Click_1(object sender, RoutedEventArgs e) 
    { 
     SingleRole role = ????; 
    } 

哪有我這樣做?我已經嘗試過FindResource和this.Resources [「SingleRole」],但我似乎無法讓它工作。

回答

1

您應該能夠使用this.Resources與投:

var provider = (ObjectDataProvider)this.Resources["SingleRole"]; 
SingleRole role = provider.ObjectInstance as SingleRole; 
if (role != null) 
{ 
    // Use it here, as it was found properly 
} 
+0

感謝您的快速響應。我知道這很簡單,但我浪費太多時間試圖獲得它。完美的作品。 – dmaruca

0

這應該工作 -

var a = this.FindResource("SingleRole"); 
相關問題