如何在自定义控件库中使用资源字典?

3

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

<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中只能合并控件模板)。
2个回答

4
你需要在每个控件中合并它们,如果你有嵌套的控件,则需要在最顶层的控件中合并它们。
<UserControl.Resources>
   <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
           <ResourceDictionary Source="pack://Application:,,,/MyControls;component/Styles/CusTextBox.xaml"/>
       </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</UserControl.Resources>

1

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

Background="{DynamicResource GrayColor1}" 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接