Listbox ItemTemplate Selector does not pick a template

后端 未结 1 1467
眼角桃花
眼角桃花 2021-01-17 21:47

I am trying to use an ItemTemplateSelector on a listbox within a grid that I am creating on a different file to later be called by the MainWindow.

Here is my DataTe

相关标签:
1条回答
  • 2021-01-17 21:55

    @Rachel is right. Your DataTemplateSelector only gets invoked once at load pretty much and not for INPC changes.

    What you can do for what you require is use a ListBoxItemStyle with DataTrigger switching the Template used

    something like:

    <ControlTemplate x:Key="greenItemTemplate">
      <Border BorderBrush="Green"
              BorderThickness="3">
        <StackPanel HorizontalAlignment="Stretch">
          <TextBlock Text="{Binding Path=GroupName}" />
          <TextBlock Text="{Binding Path=myType}" />
        </StackPanel>
      </Border>
    </ControlTemplate>
    <ControlTemplate x:Key="redItemTemplate">
      <Border BorderBrush="Red"
              BorderThickness="3">
        <StackPanel HorizontalAlignment="Stretch">
          <TextBlock Text="{Binding Path=GroupName}" />
          <TextBlock Text="{Binding Path=myType}" />
        </StackPanel>
      </Border>
    </ControlTemplate>
    <ControlTemplate x:Key="yellowItemTemplate">
      <Border BorderBrush="Yellow"
              BorderThickness="3">
        <StackPanel HorizontalAlignment="Stretch">
          <TextBlock Text="{Binding Path=GroupName}" />
          <TextBlock Text="{Binding Path=myType}" />
        </StackPanel>
      </Border>
    </ControlTemplate>
    <Style x:Key="MyListBoxItemStyle"
            TargetType="{x:Type ListBoxItem}">
      <Setter Property="Template"
              Value="{DynamicResource greenItemTemplate}" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding myType}"
                      Value="c">
          <Setter Property="Template"
                  Value="{DynamicResource redItemTemplate}" />
        </DataTrigger>
        <DataTrigger Binding="{Binding myType}"
                      Value="b">
          <Setter Property="Template"
                  Value="{DynamicResource yellowItemTemplate}" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
    

    and usage:

    <ListBox ItemContainerStyle="{StaticResource MyListBoxItemStyle}"
             ItemsSource="{Binding myCollectionOfMyClassObjects}" 
             Name="listBox1"
             HorizontalContentAlignment="Stretch" />
    
    0 讨论(0)
提交回复
热议问题