【问题标题】:How to Get Style from Resource Dictionary in code-behind into UserControlLibrary?如何从代码隐藏中的资源字典中获取样式到 UserControlLibrary?
【发布时间】:2013-08-12 15:02:45
【问题描述】:

我有一个用户控件库,其中包含一些资源字典。代码:

<ResourceDictionary   ... >
    <LinearGradientBrush x:Key="MyButtonBackground" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FF654073" Offset="0.084"/>
        <GradientStop Color="#FF8A6093" Offset="0.929"/>
    </LinearGradientBrush>


    <Style x:Key="MyButtonStyle" TargetType="{x:Type MyButton}" >
        <Setter Property="Background" Value="{StaticResource ResourceKey=MyButtonBackground}" />
        <Setter Property="Foreground" Value="White" />
    </Style>
</ResourceDictionary>

然后我有一个类来加载资源字典。基本上:

return (ResourceDictionary)Application.LoadComponent(new System.Uri("/MyAssembly;component/Themes/Default.xaml", System.UriKind.Relative))

现在,在 UserControl 类中,获取 ResourceDictionary 后,我想直接加载 Style。我该怎么做?

this.Style = ((Style)MyResourceDictionary["MyButtonStyle"]); // Don't work

但是:

this.Background = ((Brush)MyResourceDictionary["MyButtonBackground"]);   // Works

【问题讨论】:

    标签: c# wpf resourcedictionary


    【解决方案1】:

    第一个例外是什么?根据您的描述,如果thisUserControl,您将遇到异常,因为您尝试应用的Style 仅适用于MyButton

    如果您尝试在 WPF 中创建自定义 Control(其方法与 UserControl 大不相同),那么您所做的工作超出了您的需要。

    首先,您将自定义控件创建为一个类(无 XAML 页面):

    public class MyButton : Button
    {
        static MyButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(MyButton),
                new FrameworkPropertyMetadata(typeof(MyButton)));  
        }
    }
    

    然后,在您的RessourceDictionary 中,从Style 中删除x:Key

    <Style TargetType="{x:Type MyButton}" >
        <Setter Property="Background" Value="{StaticResource ResourceKey=MyButtonBackground}" />
        <Setter Property="Foreground" Value="White" />
    </Style>
    

    最后,您的ResourceDictionary 需要包含在Project_Root\Themes\generic.xaml 主题字典中。然后,您根本不需要从代码中获取资源。

    如需进一步阅读,CodeProject 有一个非常好的创建自定义 WPF 控件的教程。

    【讨论】:

    • "this",在我的示例中,是 MyButton : UserControl 类。
    • 好的,那么你遇到了什么异常?
    • 所以在代码后面显式设置Background 有效,但不应用Style?听起来您在 XAML 中显式设置属性。优先级高于Style 值。
    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多