不知道我在这里做错了什么。
我在Colors
中定义了ResourceDictionary
:Colors.xaml
:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="Normal">#FF404040</Color>
</ResourceDictionary>
然后在Brushes.xaml
中使用:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Colors.xaml"/>
<!-- here I may have more colors-->
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="Color" Color="{StaticResource Normal}" />
<!-- here I may have more brushes-->
</ResourceDictionary>
然后Brushes
合并在Generic.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Brushes.xaml"/>
<!-- here I may have more resources-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
现在,如果我使用Brushes
,就像这样说Border
Style
:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="BorderContainer" TargetType="{x:Type Border}">
<Setter Property="Background" Value="{StaticResource Color}"/>
</Style>
</ResourceDictionary>
我必须使用它作为DynamicResource
,但如果用作StaticResource
然后我在运行时遇到此错误:
{DependencyProperty.UnsetValue}' is not a valid value for property 'Background'
我希望在我的应用程序中随处使用StaticResource for Brushes。
如果要在ResourceDictionary中使用StaticResource,则需要将Brushes.xaml ResourceDictionary合并到ResourceDictionary中,您可以在其中定义Border样式,就像在Brushes.xaml中使用Colors.xaml一样:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- "Include" Brushes -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Brushes.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="BorderContainer" TargetType="{x:Type Border}">
<Setter Property="Background" Value="{StaticResource Color}" />
</Style>
</ResourceDictionary>
有关Static-和DynamicResource之间差异的更多信息,请参阅this answer。