我想创建一个类似于Microsoft Outlook的窗口标题。
为此,我创建了以下绑定:
<MultiBinding StringFormat="{}{0} - Message ({1})}"> <Binding ElementName="txtSubject" Path="Text" /> <Binding ElementName="biSendAsHtml">****</Binding> </MultiBinding>现在,我想知道如何使第二个绑定成为条件。 例如当biSendAsHtml.IsChecked等于true显示HTML,否则显示纯文本 。
I'd like to create a window title similar to Microsoft Outlook's one.
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.
最满意答案
我不确定你认为sa_ddam213的答案是否优雅,这只是可怕的。 转发器,如RV1987建议,是正确的方法,但你可以更聪明。
创建一个转换器,它接受一个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(); } }定义转换器:
<local:BoolToObjectConverter x:Key="SendAsHtmlBoolToTextConverter" TrueValue="HTML" FalseValue="Plain Text"/>并使用它:
<MultiBinding StringFormat="{}{0} - Message ({1})}"> <Binding ElementName="txtSubject" Path="Text" /> <Binding ElementName="biSendAsHtml" Path="IsChecked" Converter="{StaticResource SendAsHtmlBoolToTextConverter}"/> </MultiBinding>如果您愿意,甚至可以使TrueValue和FalseValue DependencyProperties支持Binding。
I'm not sure how you think sa_ddam213's answer is elegant, it's just scary. The converter, like RV1987 suggested, is the correct approach, but you can be a lot smarter.
Create a converter which takes a bool and converts it into options defined in the Converter definition.
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.
更多推荐
发布评论