简体   繁体   中英

Avoiding ItemTemplate Duplication With WPF Controls?

I have comboboxes that all need to use a converter:

<ComboBox>
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <ContentPresenter
            Content="{Binding Converter={StaticResource TimespanConverter}}"/>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

I'm currently pasting this everywhere I need it, but I am wondering if there is a way to avoid this duplication: to be able to do something like: <TimeSpanComboBox ...></...> or something similar?

You can define an implicit DataTemplate somewhere in your Application.Resources . ie

<DataTemplate DataType="{x:Type sys:TimeSpan}">
  <ContentPresenter
        Content="{Binding Converter={StaticResource TimespanConverter}}"/>
</DataTemplate>

You can of course also define a key and re-use it explicitly where you need it (eg ItemTemplate="{StaticResource TimeSpanTemplate}" ).

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