WPF默认主题和自定义样式不能同时使用

3

嘿,我有一个针对XP机器的WPF应用程序。问题是我们希望使用WPF XP luna主题而不是经典主题,而我们的大多数客户都在经典模式下运行。我们的客户都是内部员工,只是他们的机器配置为XP经典。

理论上,只需将以下内容添加到应用程序即可解决:

 <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0,
 Culture=neutral, PublicKeyToken=31bf3856ad364e35,
 ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" />

实际上,只要触摸任何样式(比如为TextBox添加边距),它们的样式就会恢复到经典主题。

这个显示是正确的(样式为Luna):

<TextBox  Width="80" Height="20" />

这将正确显示(样式Luna):

<TextBox Width="80" Height="20" Background="Brown">

这个显示效果不正确(经典样式),请注意,无论在样式块中有多少个节点都没有关系-零已足以混淆事情:

<TextBox.Style><Style></Style></TextBox.Style></TextBox>

长话短说,覆盖默认的操作系统主题似乎会阻止进一步使用样式。我在这里漏掉了什么?
请参见80%的答案以获取更多信息。完整的故事是:我必须提供“BasedOn”设置。不幸的是,这意味着我们无法覆盖,比如文本框,而不会导致循环。定义:
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Margin" Value="0,2,0,2" />
    :
</Style>

如果不使用命名样式,可能会导致错误:“属性表达式中检测到循环”。我选择的解决方法是强制使用命名样式。例如:

    <Style x:Key="TextBase"  TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter Property="Margin" Value="0,2,0,2" />
        :
    </Style>

<Style x:Key="Text25Chars" TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBase}">
    <Setter Property="Margin" Value="0,2,0,2" />
    :
</Style>
1个回答

3

试试这个:

<TextBox>
    <TextBox.Style>
        <Style BasedOn="{StaticResource {x:Type TextBox}}">
        </Style>
    </TextBox.Style>
</TextBox>

编辑:我忘记了TargetType,这对我有用:

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral,
                            PublicKeyToken=31bf3856ad364e35,
                            ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" />
    </Window.Resources>
        <TextBox>
            <TextBox.Style>
                <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
                    <Setter Property="Foreground" Value="Blue" />
                </Style>
            </TextBox.Style>
            tototototottototo
        </TextBox>
</Window>

你是一个英雄。添加BasedOn修复了问题。 - dave

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