【问题标题】:In WPF, Is there any way to combine two Style for one control?在 WPF 中,有没有办法为一个控件组合两种样式?
【发布时间】:2011-06-11 00:22:18
【问题描述】:

我的情况如下。

我有一个 App.xaml,其中包含这样的 ListView 样式:

<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 中这样说:

 <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 的事件。

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

有什么办法可以解决问题并实现吗?

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    样式有一个BasedOn 属性:

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

    顺便说一句:&lt;Style x:Key="{x:Type ListViewItem}" 似乎有点奇怪。 x:Key 应该是 xaml 字典中的唯一键 - 通常是字符串。

    【讨论】:

    • 非常感谢您的快速回答。哦,那是真的。 x:Key 也很奇怪。非常感谢。 :)
    【解决方案2】:

    如果 BasedOn 属性符合您的需求,那么它就是最佳选择。不过,对于更复杂的场景,the solution referred to in this question 之类的内容更加灵活。

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2020-03-06
      • 2011-04-25
      • 1970-01-01
      相关资源
      最近更新 更多