在 WPF 中,有没有办法将两个 Style 组合为一个控件? [英] In WPF, Is there any way to combine two Style for one control?

查看:33
本文介绍了在 WPF 中,有没有办法将两个 Style 组合为一个控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况如下.

我有一个 App.xaml,其中包含 ListView 的样式,如下所示:

I have a App.xaml which includes Style for ListView like this:

<Style x:Key="{x:Type ListViewItem}" TargetType="ListViewItem">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
              ...

但是,我想在另一个 xaml 中添加一些样式,让我们在 Window.xaml 中这样说:

However, I wanna add some styles into another xaml, let's say in Window.xaml like this:

 <ListView AlternationCount="2" Background="#FFECECEC">
    <ListView.Resources>
        <Style x:Key="{x:Type ListViewItem}" TargetType="{x:Type ListViewItem}">
            <EventSetter Event="PreviewMouseDoubleClick" Handler="OnPreviewMouseDoubleClick" />
        </Style>
    </ListView.Resources>
 </ListView>

所以,我想要做的是在 App.xaml 中将基本设计的样式定义为默认样式.然后,添加一些修改,例如添加上下文菜单、从每个 xaml 添加事件.

So, what I want to do is define style for base design in App.xaml as Default style. Then, add some modify such as adding a context menu, adding events from each xaml.

但是,通过上述实现,App.xaml 中定义的 Style 将被 Window.xaml 中定义的 Style 覆盖.

But, with above implementation, Style defined in App.xaml will be overwrote by Style defined in Window.xaml.

有没有办法解决问题并实现它?

Is there any way to solve the issue and achieve it?

推荐答案

样式有一个 BasedOn 属性:

<Style x:Key="Style1">
...
</Style>

<Style x:Key="Style2" BasedOn="{StaticResource Style1}">
...
</Style>

顺便说一句:<Style x:Key="{x:Type ListViewItem}" 看起来有点奇怪.x:Key 应该是 xaml 字典中的唯一键 - 通常是字符串.

Btw: <Style x:Key="{x:Type ListViewItem}" seems a bit weird. The x:Key should be a unique key in a xaml dictionary - usually a string.

这篇关于在 WPF 中,有没有办法将两个 Style 组合为一个控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆