【问题标题】:Is it possible to return more than one value from an ivalueconverter in wpf?是否可以从 wpf 中的 ivalueconverter 返回多个值?
【发布时间】:2012-06-29 14:12:41
【问题描述】:

我有一个 wpf 列表框,它实现了一个包含 TextBlock 的 DataTemplate。

    <local:BooleanToFontColorConverter x:Key="boolToFontColor" />
    <DataTemplate x:Key="ListBox_DataTemplateSpeakStatus">
            <Label Width="Auto">
                    <TextBlock Foreground="{Binding Path=myProperty, Converter={StaticResource boolToFontColor}}" />
            </Label>
    </DataTemplate>

我手头的任务是改变“myProperty”,我希望字体的颜色不同。我的转换器如下所示:

public class BooleanToFontColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                  CultureInfo culture)
    {
        if (value is Boolean)
        {
            return ((bool)value) ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black);
        }

        return new SolidColorBrush(Colors.Black);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这行得通。更改绑定属性时,字体颜色(前景)将变为红色。

我的问题是:我希望我的字体变为红色、粗体和斜体。我知道这可以通过使用 textblock 内联来实现,但是是否可以使用我的转换器来完成所有这三件事?

感谢所有有想法和见解的人做出回应。

【问题讨论】:

    标签: c# wpf xaml datatemplate ivalueconverter


    【解决方案1】:

    不要为此使用转换器,请使用DataTrigger 并为属性添加三个相应的Setters

    (您可以返回多个对象,但这毫无意义,因为所有这些属性都只接受一个对象。另一种方法是使用Binding.ConverterParameter,然后您可以在转换器上切换以返回正确的值对于正确的属性,你仍然需要三个绑定,每个都有不同的参数,这非常丑)

    【讨论】:

    • 感谢您的快速评论。我将研究如何使用 DataTrigger!
    • 谢谢 Marc,我知道这就是这个网站的运作方式。我花了一些时间调查 DataTriggers,看看这是否真的能解决我的问题。我已决定不使用 DataTriggers,但如果我选择使用它们会很好。
    猜你喜欢
    • 2014-10-23
    • 2013-02-23
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多