UserControl.Resources 中定义的资源无法查看代码中 MergedDictionaries 集中定义的元素

发布于 2024-11-18 15:55:04 字数 724 浏览 9 评论 0原文

DefaultStyles 包含所有 TextBoxes 的 DefaultStyle

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        Resources.MergedDictionaries.Add(new DefaultStyles());
        InitializeComponent();
    }
}

然后是 Xaml,我继承该样式并添加更多内容:

<UserControl.Resources>
    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter Property="Foreground" Value="Green "/>
    </Style>
</UserControl.Resources>

这会抛出一个 StackOverFlowException 因为我的 DefaultStyle 未找到,因此它尝试自引用。

为什么样式看不到合并字典中的默认样式?

DefaultStyles contains a DefaultStyle for all TextBoxes:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        Resources.MergedDictionaries.Add(new DefaultStyles());
        InitializeComponent();
    }
}

Then the Xaml, I inherit the style and add a little more:

<UserControl.Resources>
    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter Property="Foreground" Value="Green "/>
    </Style>
</UserControl.Resources>

This throws a StackOverFlowException as my DefaultStyle is not found, and so it trys to self reference.

Why can't the Style see the default styles in the merged dictionary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

物价感观 2024-11-25 15:55:04

它看不到它,因为它本质上正在取代它。 InitializeComponent 方法调用将用您在 XAML 中定义的字典替换您在构造函数中引用的字典。

基本上,你做错了。为什么你不能这样做:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DefaultStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            ...
        </Style>
    </ResourceDictionary>
</UserControl.Resources>

It can't see it because it's essentially replacing it. The InitializeComponent method call will replace the dictionary you refer to in your ctor with the dictionary you define in your XAML.

Basically, you're doing it wrong. Why can't you just do this:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DefaultStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            ...
        </Style>
    </ResourceDictionary>
</UserControl.Resources>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文