WPF绑定到两个属性

mo *_*laz 22 wpf binding

我有一个具有Message属性的WPF控件.

我目前有这个:

 <dxlc:LayoutItem >
            <local:Indicator Message="{Binding PropertyOne}" />
 </dxlc:LayoutItem>
Run Code Online (Sandbox Code Playgroud)

但我需要将该Message属性绑定到两个属性.

显然不能这样做,但这可以帮助解释我想要的是什么:

<dxlc:LayoutItem >
            <local:Indicator Message="{Binding PropertyOne && Binding PropertyTwo}" />
 </dxlc:LayoutItem>
Run Code Online (Sandbox Code Playgroud)

Ana*_*aev 31

尝试使用MultiBinding:

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

例:

XAML

<TextBlock>
   <TextBlock.Text>
       <MultiBinding Converter="{StaticResource myNameConverter}"
                     ConverterParameter="FormatLastFirst">
          <Binding Path="FirstName"/>
          <Binding Path="LastName"/>
       </MultiBinding>
   </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

Converter

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是实现这一目标的极其冗长的方法。 (2认同)

adP*_*age 29

<TextBlock.Text>
    <MultiBinding StringFormat="{}{0} {1}">
        <Binding Path="FirstName"/>
        <Binding Path="LastName"/>
    </MultiBinding>
</TextBlock.Text>
Run Code Online (Sandbox Code Playgroud)


Roh*_*ats 5

您无法And在XAML中执行操作.

在视图模型类中创建包装器属性,该属性将返回两个属性并与该属性绑定.

public bool UnionWrapperProperty
{
   get
   {
      return PropertyOne && PropertyTwo;
   }
}
Run Code Online (Sandbox Code Playgroud)

XAML

<local:Indicator Message="{Binding UnionWrapperProperty}" />
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用MultiValueConverter.将两个属性传递给它,然后从转换器返回和值.

  • 是啊.但OP没有提到任何问题,因为我们不能`&&`字符串(或所有类型).所以,只是假设OP想要bool财产.一旦OP清除图片,将更新. (2认同)