StaticResource错误:“ {DependencyProperty.UnsetValue}”不是属性的有效值

时间:2019-03-25 10:59:24

标签: c# wpf

不知道我在做什么错了。

我在Colors中定义了ResourceDictionaryColors.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。

1 个答案:

答案 0 :(得分:1)

如果要在ResourceDictionary中使用StaticResource,则需要将Brushes.xaml ResourceDictionary合并到定义边框样式的ResourceDictionary中,就像在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>

有关StaticResource和DynamicResource之间的区别的更多信息,请参见this answer

相关问题