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



>我的样式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>
在此用户控件

的代码隐藏文件中,我正在尝试获取该样式并将其应用于在同一用户控件中定义的内容控件。

这是我的用户控制.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();

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

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

在这种情况下,您可以创建新ContentControl,但不分别添加到当前可视化树中,它不可见。

此外,UserControl 中没有属性testControl,因为.用于访问 Class 属性的符号,因此在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
    }            
}

最新更新