首页 > 解决方案 > 是否可以在 WPF 的 MultiBinding QuickConverter 中使用带有参数的经典转换器?

问题描述

是否可以在 WPF 中使用带有 QuickConverter MultiBinding 参数的经典转换器?

更清楚地说,我想绑定 TextBlock 的 Text 属性以显示如下文本:

<MyApplication> + ' v' + <1.0>

MyApplication来自字符串资源Resources.String2251.0可能来自IValueConverter我可以将参数传递给的类类型myParameter。我尝试了下面的 XAML 代码,

<TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $V1',
 V0={x:Static resx:Resources.String225},
 V1={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>

使用以下转换器:

public class ProgramVersionConverter : IValueConverter
{
    public static Func<string, string> GetApplicationExeVersion;

    /// <summary>
    /// Returns version of the executable
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return GetApplicationExeVersion?.Invoke((string)parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("ProgramVersion converter ConvertBack not supported.");
    }
}

GetApplicationExeVersion设置为代码另一部分中的方法,此处不需要。

但是我在运行时遇到了这个异常:

System.Windows.Markup.XamlParseException:
'Unable to set' Binding 'on property' V1 'of type' MultiBinding '.
A 'Binding' can only be defined on a DependencyProperty of a DependencyObject. '

我是在正确的方式还是不可能做到这一点?

感谢您的关注。

标签: c#wpfparameter-passingconvertersmultibinding

解决方案


当然可以。
如果要添加一个值作为 a System.Windows.Data.Binding(或System.Windows.Data.MultiBinding等)的结果,则必须使用P0...P9的属性之一QuickConverter.MultiBinding,因为它们接受绑定表达式。V0...V9属性接受常量值,不接受绑定表达式。

<TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $P0',
 V0={x:Static resx:Resources.String225},
 P0={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>

推荐阅读