在WPF中从c#代码设置静态样式资源

时间:2014-03-31 04:34:48

标签: c# wpf xaml wpf-controls

我的样式test被定义为UserControl中ResourceDictionary的资源,如下所示:

<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的代码隐藏文件中,我试图获取该样式并将其应用于内容控件,该内容控件在同一UserControl中定义。

这是我的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();

在调试模式下,我看到了找到的样式。也可以通过搜索使用其键/名称找到模板控件。但它们不会被展示出来。它只显示一个空的用户控件,没有我在样式中定义的模板的任何控件。

我希望你能帮助我,并提前致谢!

1 个答案:

答案 0 :(得分:1)

在这种情况下,您创建新的ContentControl,但不分别添加到当前的VisualTree,它不可见。

此外,UserControl中没有属性testControl,因为.符号用于访问Class的属性,因此在m之前删除testControl或使用{ {1}}代替:

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();