WPF 绑定到两个属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23225751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF binding to two properties
提问by mo alaz
I have a WPF control that has a Message
property.
我有一个具有Message
属性的 WPF 控件。
I currently have this:
我目前有这个:
<dxlc:LayoutItem >
<local:Indicator Message="{Binding PropertyOne}" />
</dxlc:LayoutItem>
But i need that Message
property to be bound to two properties.
但我需要将该Message
属性绑定到两个属性。
Obviously can't be done like this, but this can help explain what it is I want:
显然不能这样做,但这可以帮助解释我想要的是什么:
<dxlc:LayoutItem >
<local:Indicator Message="{Binding PropertyOne && Binding PropertyTwo}" />
</dxlc:LayoutItem>
回答by adPartage
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
回答by Anatoliy Nikolaev
Try use the MultiBinding
:
尝试使用MultiBinding
:
Describes a collection of Binding objects attached to a single binding target property.
描述附加到单个绑定目标属性的 Binding 对象的集合。
Example:
例子:
XAML
XAML
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myNameConverter}"
ConverterParameter="FormatLastFirst">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Converter
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;
}
}
回答by Rohit Vats
You can't do And
operation in XAML.
您不能And
在 XAML 中进行操作。
Create wrapper property in your view model class which will return and of two properties and bind with that property instead.
在您的视图模型类中创建包装器属性,它将返回两个属性的 和 并改为与该属性绑定。
public bool UnionWrapperProperty
{
get
{
return PropertyOne && PropertyTwo;
}
}
XAML
XAML
<local:Indicator Message="{Binding UnionWrapperProperty}" />
Another approach would be to use MultiValueConverter
. Pass two properties to it and return And value from the converter instead.
另一种方法是使用MultiValueConverter
. 将两个属性传递给它并从转换器返回 And 值。