【问题标题】:Is it possible to send as parameter an attached property on a multibiding?是否可以在多标中将附加属性作为参数发送?
【发布时间】:2015-06-23 12:18:06
【问题描述】:

是否可以使用附加属性作为多重绑定的参数?怎么样?

我需要使用附加属性的值来更改绑定到 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。

【问题讨论】:

    标签: c# wpf


    【解决方案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];
    

    【讨论】:

    • 谢谢!我尝试过类似的东西,但不太正确,我也不确定转换器中 myProperty 的类型,直接是布尔值是有道理的。
    猜你喜欢
    • 2011-12-04
    • 2011-06-27
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    相关资源
    最近更新 更多