pchajer
pchajer

Reputation: 1584

WPF MultiBinding same converter with different binding path

I have ten UI Controls of the same type in a UI and all will be using same multi binding converter.

The problem is I can not create a common style for multibinding which I can apply to all UI controls to avoid duplicate code, as each control will use a different binding property to pass as a Binding to converter.

Is there any way in WPF we can avoid duplicate code for this scenario?

Upvotes: 1

Views: 1270

Answers (2)

Louis Kottmann
Louis Kottmann

Reputation: 16618

You can extend MarkupExtension, which allows you to define a custom Converter wrapper and then just call it with the 2 Paths.

Edit: in your case it's probably best to inherit directly from MultiBinding and set sensible defaults in the constructor.

Upvotes: 2

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26268

I assume you have something like this:

<Button>
  <Button.Content>
     <MultiBinding Converter="{StaticResource conv}">
       <Binding Path="COMMON" />
       <Binding Path="SPECIFIC1" />
     </MultiBinding>
  </Button.Content>
</Button>    
<Button>
  <Button.Content>
     <MultiBinding Converter="{StaticResource conv}">
       <Binding Path="COMMON" />
       <Binding Path="SPECIFIC2" />
     </MultiBinding>
  </Button.Content>
</Button>
<Button>
  <Button.Content>
     <MultiBinding Converter="{StaticResource conv}">
       <Binding Path="COMMON" />
       <Binding Path="SPECIFIC3" />
     </MultiBinding>
  </Button.Content>
</Button>

and so on... this looks ugly, I agree. I am not aware of any alternatives, however by thinking a little, you could create(imo) a little better solution:

just create new CommonMultiBindings.xaml; which includes:

<MultiBinding Converter="{StaticResource conv}">
 </MultiBinding>

and voila, done. Now just reference it as CommonMultiBindings object and use it as:

<Button.Content>
  <CommonMultiBindings>
      <!--Actual bindings here-->
  </CommonMultiBindings>
</Button.Content>

you can take it further by factoring "" into the CommonMultiBindings and adding new property(UserBindings) which will be used to synchronize between Bindings property.

Ideally, you would want to create a custom MultiBinding class which has style property. Then you could do something like this + combined with "custom" default bindings which are automatically added to "Bindings" collection

<Grid.Resources>
  <Style TargetType="MultiBinding">
    <Setter Property="Converter" Value="{StaticResource conv}" />
  </Style>
</Grid.Resources>

Upvotes: 1

Related Questions