[英]Conditional XAML-Binding
I'd like to create a window title similar to Microsoft Outlook's one. 我想创建一个类似于Microsoft Outlook的窗口标题。
For that, I've created the following binding: 为此,我创建了以下绑定:
<MultiBinding StringFormat="{}{0} - Message ({1})}">
<Binding ElementName="txtSubject" Path="Text" />
<Binding ElementName="biSendAsHtml">****</Binding>
</MultiBinding>
Now I'd like to know how I can make the second binding conditional. 现在,我想知道如何使第二个绑定成为条件。 Such as when
biSendAsHtml.IsChecked
equals true
display HTML else display Plain Text . 例如当
biSendAsHtml.IsChecked
等于true
显示HTML,否则显示纯文本 。
Create a IValueConverter and use it in your second binding - 创建一个IValueConverter并在第二个绑定中使用它 -
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return (bool)value ? "HTML" : "Your Text";
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Here goes your XAML - 这是你的XAML -
<MultiBinding StringFormat="{}{0} - Message ({1})}">
<Binding ElementName="txtSubject" Path="Text" />
<Binding ElementName="biSendAsHtml" Path="IsChecked"
Converter="{StaticResource Myconverter}"/>
</MultiBinding>
I'm not sure how you think sa_ddam213's answer is elegant, it's just scary. 我不确定你认为sa_ddam213的答案是否优雅,这只是可怕的。 The converter, like RV1987 suggested, is the correct approach, but you can be a lot smarter.
转发器,如RV1987建议,是正确的方法,但你可以更聪明。
Create a converter which takes a bool and converts it into options defined in the Converter definition. 创建一个转换器,它接受bool并将其转换为Converter定义中定义的选项。
public class BoolToObjectConverter : IValueConverter
{
public object TrueValue { get; set; }
public object FalseValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert.ToBoolean(value) ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Define the Converter: 定义转换器:
<local:BoolToObjectConverter x:Key="SendAsHtmlBoolToTextConverter"
TrueValue="HTML"
FalseValue="Plain Text"/>
And use it: 并使用它:
<MultiBinding StringFormat="{}{0} - Message ({1})}">
<Binding ElementName="txtSubject" Path="Text" />
<Binding ElementName="biSendAsHtml" Path="IsChecked"
Converter="{StaticResource SendAsHtmlBoolToTextConverter}"/>
</MultiBinding>
If you want you could even make TrueValue and FalseValue DependencyProperties to support Binding. 如果你想要甚至可以使TrueValue和FalseValue DependencyProperties支持Binding。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.