如何在WPF中将变量作为Converterparameter传递

Vah*_*hid 6 c# wpf

我试图将后面的代码中定义的变量传递给ConverterParameter.我将在转换器中使用此参数然后决定某些单位转换.问题是我不知道如何通过这个.变量不是静态的.

<TextBox Text="{Binding MinimumRebarsVerticalDistance, Converter={StaticResource LengthConverter}, ConverterParameter={CurrentDisplayUnit}}"/>
Run Code Online (Sandbox Code Playgroud)

代码背后:

private Units currentDisplayUnit;
public Units CurrentDisplayUnit
{
    get { return currentDisplayUnit; }
    set
    {
        currentDisplayUnit = value;
        RaisePropertyChanged("CurrentDisplayUnit");
    }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*nis 14

你可以用它MultiBinding来达到这个目的.
首先,实施LengthConverterIMultiValueConverter:

public sealed class LengthConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // values array will contain both MinimumRebarsVerticalDistance and 
        // CurrentDisplayUnit values
        // ...
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

二,绑定多绑定TextBox.Text:

        <TextBox.Text>
            <MultiBinding Converter="{StaticResource LengthConverter}">
                <Binding Path="MinimumRebarsVerticalDistance"/>
                <Binding Path="CurrentDisplayUnit" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}"/>
            </MultiBinding>
        </TextBox.Text>
Run Code Online (Sandbox Code Playgroud)

注1:RelativeSource.AncestorType取决于CurrentDisplayUnit声明属性的位置(样本用于后面的窗口代码).

注2:看起来CurrentDisplayUnit应该是一个视图模型属性.