2014-03-31 50 views
0
設置一個靜態的樣式資源

我的風格test是在用戶控件一個ResourceDictionary定義爲一種資源,就像這樣:從C#代碼在WPF

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

<Style x:Key="test" TargetType="ContentControl"> 
    <!--<Setter Property="Visibility" Value="Visible" />--> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ContentControl"> 
       <TextBlock Text="TESTTTT" Foreground="Black"/> 
      </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</ResourceDictionary> 

用戶控件:

<ResourceDictionary> 
    <ResourceDictionary.MergedDictionaries> 
     <ResourceDictionary Source="Dictionary1.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 
</ResourceDictionary> 

在後面的代碼此用戶控件的文件我試圖獲取該樣式並將其應用於同一用戶控件中定義的內容控件。

這裏是我的UserControl.xaml:

<UserControl x:Class="WpfApplication2.MainWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      Height="350" Width="525" Loaded="Window_Loaded"> 
    <UserControl.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="Dictionary1.xaml" /> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </UserControl.Resources> 

    <Grid> 
     <ContentControl Name="testControl" /> 
    </Grid> 
</UserControl> 

,並在代碼隱藏在Loaded事件處理我寫道:

UserControl m = sender as UserControl; 
Style s = m.Resources["test"] as Style; 
// I also tried to reference style in App resources, but it didn't make any difference 
//(Style)Application.Current.FindResource("test"); 
m.testControl = new ContentControl(); 
m.testControl.Style = s; 
m.testControl.ApplyTemplate(); 

在調試模式下,我看到了發現風格。通過搜索使用他們的鍵/名稱也可以找到模板控件。但他們不會被顯示。它只是顯示一個空的用戶控件,沒有來自我在樣式中定義的模板的任何控件。

我希望你能幫助我,在此先感謝!

+0

什麼是樣式?顯示完整的示例。 –

+0

我編輯了我的帖子。當我在xaml中使用我的樣式時,它可以工作

回答

1

在這種情況下,您將創建新的ContentControl,但不會分別添加到當前的VisualTree中,它不可見。

此外,不存在屬性testControl在一個用戶控件,因爲用於訪問類的屬性.符號,因此testControl之前刪除m或使用this代替:

UserControl m = sender as UserControl; 
Style s = m.Resources["test"] as Style; 
m.testControl = new ContentControl(); // Remove this line 
m.testControl.Style = s;    // and 'm', or write like this: this.testControl.Style = s; 
m.testControl.ApplyTemplate(); 

而最後的結果是:

private void UserControl_Loaded(object sender, RoutedEventArgs e) 
{ 
    var control = sender as UserControl; 

    if (control != null) 
    { 
     Style s = control.Resources["test"] as Style; 
     testControl.Style = s; 

     // control.ApplyTemplate(); // it's not necessary in your case 
    }    
}