Reputation: 5895
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.
Upvotes: 1
Views: 6191
Reputation: 1726
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.
Upvotes: 2
Reputation: 81253
Create a IValueConverter and use it in your second binding -
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 -
<MultiBinding StringFormat="{}{0} - Message ({1})}">
<Binding ElementName="txtSubject" Path="Text" />
<Binding ElementName="biSendAsHtml" Path="IsChecked"
Converter="{StaticResource Myconverter}"/>
</MultiBinding>
Upvotes: 2