使用IValueConverter的动态样式绑定 [英] Dynamic Style Binding with IValueConverter

查看:91
本文介绍了使用IValueConverter的动态样式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一种样式,该样式在 App.xaml 中定义,在加载用户控件时会动态地设置,并且由于某种原因而没有应用该样式(也就是说,没有错误发生,只是没有应用样式。)

I am trying to set a style, which is defined in the App.xaml, dynamically when loading a user control and it's just not applying the style for some reason (i.e. there is no error occurring, it's just not applying the style).

我敢肯定这是因为我定义的绑定错误,但是我无法弄清楚我需要做些什么才能使其工作。

I'm sure it's because I've defined the binding wrong, but I'm unable to figure out what I need to do differently to get it to work.

样式我需要的是 RunningTitleBlock ,它由以下代码示例中包含的其他两种样式组成。

The style I'm after is the RunningTitleBlock and it's comprised of a couple other styles that I've included in the below code sample.

<Style TargetType="Label">
    <Setter Property="Margin" Value="4"/>
</Style>

<Style TargetType="Label"
       BasedOn="{StaticResource {x:Type Label}}"
       x:Key="HeaderBlock">
    <Setter Property="FontSize" Value="16"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Foreground" Value="White"/>
</Style>

<Style TargetType="Label"
       BasedOn="{StaticResource ResourceKey=HeaderBlock}"
       x:Key="TitleBlock">
    <Setter Property="Foreground" Value="Black"/>
</Style>

<Style TargetType="Label"
       BasedOn="{StaticResource ResourceKey=TitleBlock}"
       x:Key="RunningTitleBlock">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush StartPoint="0.0, 0.5"
                                 EndPoint="1.0, 0.5">
                <GradientStop Color="White" Offset="0.0"/>
                <GradientStop Color="Green" Offset="1.0"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
</Style>



在用户控件上绑定



I正在尝试获取 Binding 绑定到从值转换器返回的值。

Binding on the user control

I'm trying to get the Binding to bind to a value returned from a value converter.

Style="{DynamicResource ResourceKey={Binding Path=MonitoringType, Converter={StaticResource TSConverter}}}"



代码



MonitoringTypes枚举



Code

MonitoringTypes Enum

public enum MonitoringTypes
{
    Running,
    Failed,
    Paused,
    Favorites,
}



用户控制



在这里,我要连接的是<$ c $的字符串值c> MonitoringTypes 枚举值,该枚举值与一些众所周知的文本一起传递,以构建 App.xaml 中存在的样式名称。该值转换器被称为 ,返回正确的值,但是由于某种原因,样式不适用。

User Control

Here what I'm trying to do is concatenate the string value of the MonitoringTypes enum value that's passed in with some well known text to build a style name that exists in the App.xaml. The value converter is being called and returning the correct value, but for some reason the style isn't applying.

/// <summary>
/// Interaction logic for MonitorWorkflow.xaml
/// </summary>
public partial class MonitorWorkflow : UserControl
{
    public MonitorWorkflow(MonitoringTypes monitoringType)
    {
        InitializeComponent();

        this.DataContext = new MonitorWorkflowViewModel { MonitoringType = monitoringType };
    }
}

public class MonitorWorkflowViewModel
{
    public MonitoringTypes MonitoringType { get; set; }
}

public class TitleStyleValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var type = (MonitoringTypes)value;
        return string.Format("{0}TitleBlock", Enum.GetName(typeof(MonitoringTypes), type));
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.Parse(typeof(MonitoringTypes), value.ToString().Substring(0, value.ToString().IndexOf("TitleBlock")));
    }
}


推荐答案

我的建议是跳过 DynamicResource 语句,并使用 Converter 提供 Style

My suggestion would be to skip the DynamicResource statement and using the Converter provide the Style directly.

Style="{Binding Path=MonitoringType, Converter={StaticResource TSConverter}}"

TSConverter 中,您可以返回 Style 而不是字符串。像这样:

In TSConverter, you can return a Style rather than a string. Kind of like this:

public class TitleStyleValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
        System.Globalization.CultureInfo culture)
    {
        var type = (MonitoringTypes)value;
        var styleToReturn = FindResource(
            string.Format("{0}TitleBlock", 
                Enum.GetName(typeof(MonitoringTypes), type)));
        if (styleToReturn != null)
            return (Style)styleToReturn;
        else 
            return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        // not sure if you need this anymore... 
        return Enum.Parse(typeof(MonitoringTypes), value.ToString().Substring(0,
           value.ToString().IndexOf("TitleBlock")));
    }
}






这是我所做的,但是使用了以下代码。当您也回答我时,我实际上只是回答了我自己的问题。


This is what I did but with the following code instead. I actually just answered my own question while you answered it as well. Good timing!

public class TitleStyleValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var type = (MonitoringTypes)value;
        return App.Current.Resources[string.Format("{0}TitleBlock", Enum.GetName(typeof(MonitoringTypes), type))];
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.Parse(typeof(MonitoringTypes), value.ToString().Substring(0, value.ToString().IndexOf("TitleBlock")));
    }
}

这篇关于使用IValueConverter的动态样式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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