WPF绑定新复杂类型的多个属性

时间:2011-03-31 07:37:52

标签: wpf binding

是否可以在WPF中执行此类操作? 假设我有这样一个类:

class Pair
{
    public string A{get;set;}
    public string B{get;set;}
}

属性PropertyA正确绑定,PropertyB正确绑定...

<SomeControl Tag="{Pair A="{Binding Path=PropertyA}", B="{Binding Path=PropertyB}" />

1 个答案:

答案 0 :(得分:3)

您可以将MultiBinding与转换器一起使用:

<SomeControl>
    <SomeControl.Tag>
        <MultiBinding Converter="{StaticResource pairConverter}">
            <Binding Path="A" />
            <Binding Path="B" />
        </MultiBinding>
    </SomeControl.Tag>
</SomeControl>

使用此转换器:

public class PairConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Length == 2)
        {
            return new Pair { A = (string)values[0], B = (string)values[1] };
        }
        return Binding.DoNothing;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        Pair p = (Pair)value;
        return new object[] { p.A, p.B };
    }
}