1

我在 UI 中有十个相同类型的 UI 控件,并且都将使用相同的多绑定转换器。

问题是我无法为多重绑定创建一个通用样式,我可以将其应用于所有 UI 控件以避免重复代码,因为每个控件将使用不同的绑定属性作为绑定传递给转换器。

WPF中有什么方法可以避免这种情况下的重复代码吗?

4

2 回答 2

2

您可以扩展 MarkupExtension,它允许您定义一个自定义转换器包装器,然后只需使用 2 个路径调用它。

编辑:在您的情况下,最好直接从 MultiBinding 继承并在构造函数中设置合理的默认值。

于 2012-07-22T16:47:45.297 回答
1

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>
于 2012-07-22T15:50:45.053 回答