且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 绑定到两个属性

更新时间:2022-06-23 03:08:05

尝试使用 MultiBinding:

描述附加到单个绑定目标属性的 Binding 对象集合.

Describes a collection of Binding objects attached to a single binding target property.

示例:

XAML

<TextBlock>
   <TextBlock.Text>
       <MultiBinding Converter="{StaticResource myNameConverter}"
                     ConverterParameter="FormatLastFirst">
          <Binding Path="FirstName"/>
          <Binding Path="LastName"/>
       </MultiBinding>
   </TextBlock.Text>
</TextBlock>

转换器

public class NameConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string name;

        switch ((string)parameter)
        {
            case "FormatLastFirst":
                name = values[1] + ", " + values[0];
                break;
            case "FormatNormal":
                default:
                name = values[0] + " " + values[1];
                break;
        }

        return name;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string[] splitValues = ((string)value).Split(' ');
        return splitValues;
    }
}