简体   繁体   中英

Conditional XAML-Binding

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 .

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM