通过代码将MergedDictionaries添加到样式

时间:2015-11-02 16:45:35

标签: c# wpf

我在资源文件中有style

<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Colors.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <Style TargetType="TextBox" x:Key="StandardTextBox"/>
                <Setter Property="Foreground" Value="{StaticResource Color1}"/>
            </Style>
</ResourceDictionary>

(Colors.xaml包含我的brushes

我的代码使用style

ResourceDictionary TetxboxStyles = new ResourceDictionary();
TetxboxStyles.Source = (new Uri("TextboxStyles.xaml", UriKind.RelativeOrAbsolute));
Resources.MergedDictionaries.Add(TetxboxStyles);
tb_input.Style = (Style)Find("StandardTextBox");

这没有问题,但是当我通过代码而不是TextboxStyles-File动态添加Colors-Resource时它不起作用:

ResourceDictionary TetxboxStyles = new ResourceDictionary();
TetxboxStyles.Source = (new Uri("TextboxStyles.xaml", UriKind.RelativeOrAbsolute));

//Adding the Colors.xaml Resource
ResourceDictionary Colors = new ResourceDictionary();
brushes.Source = (new Uri("Colors.xaml", UriKind.RelativeOrAbsolute));
TetxboxStyles.MergedDictionaries.Add(Colors);

Resources.MergedDictionaries.Add(TetxboxStyles);
tb_input.Style = (Style)Find("StandardTextBox");

输出-错误:

System.Windows.Markup.XamlParseException

"{DependencyProperty.UnsetValue}"

1 个答案:

答案 0 :(得分:0)

我将StaticResource替换为DynamicResource并且有效