简体   繁体   中英

Using datatriggers to set the ItemsSource property in WPF

I have been trying to set the item source of a WPF control based on a enum that the data trigger is bound too.

I have been very unsucessful and I am unsure of this is the correct way to do it:

<DataTrigger Binding="{Binding EnumSetting}" Value="Test">
      <Setter TargetName="control" Property="ItemsSource" Value="{Binding Model}" />
</DataTrigger>

I have been trying different versions of the above. Could anyone help or point me in the right direction.

Should it be wrapped in "<'style'>" tags for example, I don't think it should be but I am unsure why this is not working.

Thank you.

Mainly you need to watch DP precedence , which means you may not set the ItemsSource on the ItemsControl (or sub-class of that) directly as it would override the trigger. Instead you should use a default setter.

<ItemsControl>
     <ItemsControl.Style>
          <Style TargetType="ItemsControl">
               <Setter Property="ItemsSource" Value="SomeDefaultHere"/>
               <Style.Triggers>
                   <DataTrigger ...>
                        <Setter Property="ItemsSource" Value="SomeOverrideHere"/>
                   </DataTrigger>
               </Style.Triggers>
          </Style>
    </ItemsControl.Style>
</ItemsControl>

(You probably want a style unless you are in some control template's triggers.)

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