【问题标题】:How to use resource dictionaries in custom control library?如何在自定义控件库中使用资源字典?
【发布时间】:2023-03-04 13:57:01
【问题描述】:

我创建了一个包含一些常用画笔的资源字典。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="GrayColor1" Color="#f2f2f2"/>
    <SolidColorBrush x:Key="GrayColor2" Color="#e5e5e5"/>
    <SolidColorBrush x:Key="GrayColor3" Color="#d9d9d9"/>
    ...
</ResourceDictionary>

我想在自定义控件库中的许多控件中使用它们,但我没有找到任何方法使它们可用于控件。
在普通应用程序中,我会将它们放在 App.xaml 中,但在库中没有 App.xaml 文件。
那么库中资源字典的使用方法是什么?

我已经尝试将字典合并到 /Themes/Generic.xaml 中,但没有成功:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/MyControls;component/DefaultBrushes.xaml"/>
        <ResourceDictionary Source="/MyControls;component/Styles/CustButton.xaml"/>
        <ResourceDictionary Source="/MyControls;component/Styles/CustTextBox.xaml"/>
        ...
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

但是引用资源会导致空引用(似乎在 Generic.xaml 中只能合并控件模板)。

【问题讨论】:

    标签: wpf dictionary dll custom-controls resourcedictionary


    【解决方案1】:

    您必须在每个控件中合并它们,或者如果您有嵌套控件,则在最顶层的控件中合并它们。

    <UserControl.Resources>
       <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>
               <ResourceDictionary Source="pack://Application:,,,/MyControls;component/Styles/CusTextBox.xaml"/>
           </ResourceDictionary.MergedDictionaries>
       </ResourceDictionary>
    </UserControl.Resources>
    

    【讨论】:

      【解决方案2】:

      您仍然可以在应用程序 App.xaml 中创建合并字典,但在您想要访问这些画笔的控件库中,请尝试使用 DynamicResource 而不是 StaticResource。

      Background="{DynamicResource GrayColor1}" 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-28
        相关资源
        最近更新 更多