【问题标题】:XAML Combine styles going beyond BasedOn?XAML 组合样式超越了 BasedOn?
【发布时间】:2011-08-10 08:11:53
【问题描述】:

有没有什么方法可以在 XAML 中组合多种样式来创建具有所有所需设置的新样式?

例如(伪代码);

<Style x:key="A">
 ...
</Style>

<Style x:key="B">
 ...
</Style>

<Style x:key="Combined">
 <IncludeStyle Name="A"/>
 <IncludeStyle Name="B"/>
 ... other properties.
</Style>

我知道样式有一个 BasedOn 属性,但该功能只能带您到此为止。我真的只是在寻找一种简单的方法(在 XAML 中)来创建这些“组合”样式。但就像我之前说的,我怀疑它是否存在,除非有人听说过这样的事情??

【问题讨论】:

标签: wpf xaml styles


【解决方案1】:

您可以制作自定义标记扩展,将样式属性和触发器合并为一个样式。您需要做的就是将MarkupExtension 派生类添加到您的命名空间,并定义MarkupExtensionReturnType 属性,然后您就可以开始运行了。

这是一个允许您使用“类 css”语法合并样式的扩展。

MultiStyleExtension.cs

[MarkupExtensionReturnType(typeof(Style))]
public class MultiStyleExtension : MarkupExtension
{
    private string[] resourceKeys;

    /// <summary>
    /// Public constructor.
    /// </summary>
    /// <param name="inputResourceKeys">The constructor input should be a string consisting of one or more style names separated by spaces.</param>
    public MultiStyleExtension(string inputResourceKeys)
    {
        if (inputResourceKeys == null)
            throw new ArgumentNullException("inputResourceKeys");
        this.resourceKeys = inputResourceKeys.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (this.resourceKeys.Length == 0)
            throw new ArgumentException("No input resource keys specified.");
    }

    /// <summary>
    /// Returns a style that merges all styles with the keys specified in the constructor.
    /// </summary>
    /// <param name="serviceProvider">The service provider for this markup extension.</param>
    /// <returns>A style that merges all styles with the keys specified in the constructor.</returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        Style resultStyle = new Style();
        foreach (string currentResourceKey in resourceKeys)
        {
            object key = currentResourceKey;
            if (currentResourceKey == ".")
            {
                IProvideValueTarget service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
                key = service.TargetObject.GetType();
            }
            Style currentStyle = new StaticResourceExtension(key).ProvideValue(serviceProvider) as Style;
            if (currentStyle == null)
                throw new InvalidOperationException("Could not find style with resource key " + currentResourceKey + ".");
            resultStyle.Merge(currentStyle);
        }
        return resultStyle;
    }
}

public static class MultiStyleMethods
{
    /// <summary>
    /// Merges the two styles passed as parameters. The first style will be modified to include any 
    /// information present in the second. If there are collisions, the second style takes priority.
    /// </summary>
    /// <param name="style1">First style to merge, which will be modified to include information from the second one.</param>
    /// <param name="style2">Second style to merge.</param>
    public static void Merge(this Style style1, Style style2)
    {
        if(style1 == null)
            throw new ArgumentNullException("style1");
        if(style2 == null)
            throw new ArgumentNullException("style2");
        if(style1.TargetType.IsAssignableFrom(style2.TargetType))
            style1.TargetType = style2.TargetType;
        if(style2.BasedOn != null)
            Merge(style1, style2.BasedOn);
        foreach(SetterBase currentSetter in style2.Setters)
            style1.Setters.Add(currentSetter);
        foreach(TriggerBase currentTrigger in style2.Triggers)
            style1.Triggers.Add(currentTrigger);
        // This code is only needed when using DynamicResources.
        foreach(object key in style2.Resources.Keys)
            style1.Resources[key] = style2.Resources[key];
    }
}

您的示例将通过以下方式解决:

<Style x:key="Combined" BasedOn="{local:MultiStyle A B}">
      ... other properties.
</Style>

我们通过在内置BasedOn 属性(用于样式继承)中合并另外两个样式“A”和“B”,定义了一个名为“Combined”的新样式。我们可以像往常一样选择将其他属性添加到新的“组合”样式中。

其他示例

在这里,我们定义了 4 种按钮样式,并且可以在几乎没有重复的情况下进行各种组合使用:

<Window.Resources>
    <Style TargetType="Button" x:Key="ButtonStyle">
        <Setter Property="Width" Value="120" />
        <Setter Property="Height" Value="25" />
        <Setter Property="FontSize" Value="12" />
    </Style>
    <Style TargetType="Button" x:Key="GreenButtonStyle">
        <Setter Property="Foreground" Value="Green" />
    </Style>
    <Style TargetType="Button" x:Key="RedButtonStyle">
        <Setter Property="Foreground" Value="Red" />
    </Style>
    <Style TargetType="Button" x:Key="BoldButtonStyle">
        <Setter Property="FontWeight" Value="Bold" />
    </Style>
</Window.Resources>

<Button Style="{local:MultiStyle ButtonStyle GreenButtonStyle}" Content="Green Button" />
<Button Style="{local:MultiStyle ButtonStyle RedButtonStyle}" Content="Red Button" />
<Button Style="{local:MultiStyle ButtonStyle GreenButtonStyle BoldButtonStyle}" Content="green, bold button" />
<Button Style="{local:MultiStyle ButtonStyle RedButtonStyle BoldButtonStyle}" Content="red, bold button" />

您甚至可以使用“.”语法将类型(上下文相关)的“当前”默认样式与一些其他样式合并:

<Button Style="{local:MultiStyle . GreenButtonStyle BoldButtonStyle}"/>

以上将TargetType="{x:Type Button}"的默认样式与两个补充样式合并。

信用

我在bea.stollnitz.com 找到了MultiStyleExtension 的原始想法,并对其进行了修改以支持“.”表示法以引用当前样式。

【讨论】:

  • 我已经成功地用它来组合2种样式;但是,我遇到了一个小问题。 VS 2010 WPF Designer 对这种方法存在问题。我可以完全按照此处详细描述的方式组合样式并使用 MultiStyle,并毫无问题地构建/运行代码。但是 WPF 设计者抱怨在 DataTemplate 中使用这种方法。有没有人遇到/解决过这个问题?
  • @JoeK 我遇到了完全相同的问题,并在这里发布了一个关于它的问题:stackoverflow.com/questions/8731547/…。到目前为止,我唯一的解决方案是在设计模式下禁用扩展,这不太理想。
  • 在资源字典中为点符号定义的样式中使用BasedOn 时存在错误。这是修复:IProvideValueTarget service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); if (service.TargetObject is Style) { key = ((Style)service.TargetObject).TargetType; } else { key = service.TargetObject.GetType(); }
  • 我已经修改了你的代码,所以它现在可以接受多达 10 个样式对象作为参数,而不是使用样式键进行重构 + 合并发生在构造函数中:dotnetfiddle.net/r464VS
  • 如果有人感兴趣,我把这个 Epsiloner.Wpf.Extensions.MultiStyleExtension 放到我的 WPF 相关库中:github.com/Epsil0neR/Epsiloner.Wpf.Corenuget.org/packages/Epsiloner.Wpf.Core
【解决方案2】:

您可以在样式中使用 BasedOn 属性,例如:

<Style x:Key="BaseButtons" TargetType="{x:Type Button}">
        <Setter Property="BorderThickness" Value="0"></Setter>
        <Setter Property="Background" Value="Transparent"></Setter>
        <Setter Property="Cursor" Value="Hand"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
</Style>
<Style x:Key="ManageButtons" TargetType="{x:Type Button}" BasedOn="{StaticResource BaseButtons}">
        <Setter Property="Height" Value="50"></Setter>
        <Setter Property="Width" Value="50"></Setter>
</Style>
<Style x:Key="ManageStartButton" TargetType="{x:Type Button}" BasedOn="{StaticResource BaseButtons}">
        <Setter Property="FontSize" Value="16"></Setter>
</Style>

并使用:

<Button Style="{StaticResource ManageButtons}"></Button>
<Button Style="{StaticResource ManageStartButton}"></Button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多