Kilazur
Kilazur

Reputation: 3188

How to bind a Setter in Resources to multiple controls?

I have a UserControl with, amongst other things, two ComboBoxes, which share the same IsEnabled property's definition:

<ComboBox.IsEnabled>
    <MultiBinding Converter="{StaticResource nullMultiConverter}">
        <Binding Path="ItemsSource"/>
        <Binding ElementName="aThirdIrrelevantComboBox" Path="SelectedItem"/>
    </MultiBinding>
</ComboBox.IsEnabled>

Basically, it says that if this combo box's ItemsSource is null or if aThirdIrrelevantComboBox's SelectedItem is null, this combo box's IsEnabled is false (and true elseways).

So I have two combo boxes with that same exact definition (copy-pasted). How can I avoid repeating this definition for each control that needs it?

I tried creating a Setter in my UserControl.Resources, but I don't seem to know how to bind it.

<UserControl.Resources>
    <converters:NullToEnabledMultiConverter x:Key="nullMultiConverter"/>
    <Setter Property="ComboBox.IsEnabled" x:Key="shpEnabled">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource nullMultiConverter}">
                <Binding Path="ItemsSource"/>
                <Binding ElementName="aThirdIrrelevantComboBox" Path="SelectedItem"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</UserControl.Resources>

This binding doesn't work, my combo boxes remain enabled:

<ComboBox IsEnabled=IsEnabled="{Binding Value, Source={StaticResource shpEnabled}}"/>

Upvotes: 0

Views: 655

Answers (1)

Sheridan
Sheridan

Reputation: 69959

Put your Setter into a Style and name that instead:

<Style x:Key="ShpEnabledStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="ComboBox.IsEnabled">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource nullMultiConverter}">
                <Binding Path="ItemsSource"/>
                <Binding ElementName="aThirdIrrelevantComboBox" Path="SelectedItem"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

Then apply that Style to the relevant ComboBox(es):

<ConboBox Style="{StaticResource ShpEnabledStyle}" ... />

Upvotes: 1

Related Questions