是否可以在多重绑定中作为参数发送附加属性?

时间:2015-04-16 20:56:04

标签: c# wpf

是否可以使用附加属性作为Multibinding的参数?怎么样?

我需要使用附加属性的值来更改我绑定到TextBlock的文本。

我的代码与此类似:

TextBlock绑定

 <TextBlock x:Name="myTxt" 
        wpfApplication2:TextBlockAttachedProperties.MyProperty="true">
<TextBlock.Text>
    <MultiBinding Converter="{StaticResource CustomConverter}"  Mode="TwoWay" NotifyOnValidationError="true">
        <Binding Path="Test"/>
        <Binding ElementName="myTxt" Path="MyProperty" Mode="OneWay"/>
    </MultiBinding>
</TextBlock.Text>

我的转换器:

转换代码

 public class CustomConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double? value = null;

        value = values[0] as double?;
        DependencyProperty myProperty= null;

        if (values.Count() > 1 && values[1] != DependencyProperty.UnsetValue) 
            //Do something

        if (myProperty!= null )
        {
            //here do something with the value using the attached property
            var convertedValue = value; 

            return convertedValue;
        }

        return value;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        object[] values = { value };
        return values;
    }
}

但是,由于我不知道如何将附加属性作为Multibinding的参数传递,因此转换器始终会获取DependencyProperty.UnsetValue。

1 个答案:

答案 0 :(得分:1)

MultiBinding应如下所示,其中附加属性的名称写在括号中(参见PropertyPath XAML Syntax):

<MultiBinding Converter="{StaticResource CustomConverter}">
    <Binding Path="Test"/>
    <Binding Path="(local:TextBlockAttachedProperties.MyProperty)"
             RelativeSource="{RelativeSource Self}"/>
</MultiBinding>

此外,值转换器中的属性类型不是DependencyProperty,而只是bool(即TextBlockAttachedProperties.MyProperty的类型):

bool myProperty = (bool)values[1];