使用StyleSelector一个按钮按钮、StyleSelector

2023-09-02 10:33:22 作者:终究过了期

我有一个要求,基于数据的值更改按钮的样式。它看起来像一个StyleSelector将工作完美,但似乎没有成为一个方法来设置一个用于按钮。

I have a requirement to change a button's style based on a value in the data. It looks like a StyleSelector would work perfectly but there doesn't seem to be a way to set one for a button.

有没有办法从数据动态地设置一个按钮样式?甚至一个纯粹的XAML的方法吗?

Is there a way to set a button style dynamically from data? Maybe even a pure XAML approach?

推荐答案

您可以将您的按钮样式在资源字典和绑定样式为按钮并使用一个转换器

You could place your Button Styles in a Resource Dictionary and bind the Style for the Button and use a Converter

ButtonStyles.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="ButtonStyle1" TargetType="Button">
        <Setter Property="Background" Value="Green"/>
        <Setter Property="FontSize" Value="12"/>
    </Style>
    <Style x:Key="ButtonStyle2" TargetType="Button">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="FontSize" Value="14"/>
    </Style>
</ResourceDictionary>

那么对于按钮,有此要求你绑定风格感兴趣的财产

Then for the Button that has this requirement you bind Style to the property of interest

<Button ...
        Style="{Binding Path=MyDataProperty,
                        Converter={StaticResource ButtonStyleConverter}}"/>

而在转换器,您基于价值加载ButtonStyles资源字典,并返回所需的伴奏

And in the Converter you load the ButtonStyles Resource Dictionary and return the desired Style based on the value

public class ButtonStyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Uri resourceLocater = new Uri("/YourNameSpace;component/ButtonStyles.xaml", System.UriKind.Relative);
        ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
        if (value.ToString() == "Some Value")
        {
            return resourceDictionary["ButtonStyle1"] as Style;
        }
        return resourceDictionary["ButtonStyle2"] as Style;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}