【问题标题】:Xaml Default Style for TypeXaml 类型的默认样式
【发布时间】:2016-06-14 21:37:37
【问题描述】:

我为应用程序中的所有图像设置了默认样式(放入应用程序资源中):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

        <Setter Property="Opacity" Value="0.3"/> <!--To obviously see that it works-->
        <Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
        <Setter Property="SnapsToDevicePixels" Value="True" />
    </Style>
</ResourceDictionary>

如果我在其他地方有类似风格的图片

<Image>
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            ... set some other properties here
        </Style>
    </Image.Style>
</Image>

未应用基本样式。如果我放一个

BasedOn="{StaticResource {x:Type Image}}"

一切都按(我)预期的那样工作。

有没有办法应用默认样式而无需遍历我的所有 xaml 并将 BasedOn 添加到每个样式图像?


编辑:

我经常有一些数据触发器,比如:

<Image>
    <Image.Style>
        <Style TargetType="{x:Type Image}" >
            <Style.Triggers>
                <DataTrigger Binding="{Binding Type}" Value="VAR1">
                    <Setter Property="Source" Value="/MyApp;component/Resources/Var1.png"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Type}" Value="VAR2">
                    <Setter Property="Source" Value="/MyApp;component/Resources/Var2.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    因此,通过声明新样式,您实际上覆盖了默认样式。 BasedOn 是从另一个样式模板(在本例中为默认)继承元素所必需的,因此您看到的是预期结果。

    但是,您可以放弃额外的模板,只在实例级别声明属性,这样您就不需要引用另一个模板。

    所以不是像现在这样的新模板;

    <Image>
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                ... set some other properties here
            </Style>
        </Image.Style>
    </Image>
    

    你只需要内联这样的属性;

    <Image Property="Value" Property="Value" Property="Value"/>
    

    那么Image 仍将继承默认值,但特定属性只会在实例而不是整个模板处被覆盖。

    希望这会有所帮助。

    【讨论】:

    • 得到你的想法!但我经常使用Style.TriggersDataTrigger 来切换一些图像源。我想这很难写成内联...
    • 我不确定我理解你的意思,可能需要一个例子。无论哪种方式,一旦您声明了新样式,除非您使用BasedOn 引用它,否则原始样式将被覆盖,这就是它的方式。 ://
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多