Search code examples
c#wpfxamllistviewword-wrap

WPF Textwrapping trigger on ListView IsSelected state


I am making a xaml app that has a listview. When the text is long, I am using textTrimming to shorten it but when the user clicks on the item I want the TextWrapping attribute to change from nowrap to wrap. Here is what I have so far:

<Listview>
 <Listview.View>
   <GridView>
    <GridViewColumn Header="Name">
     <GridViewColumn.CellTemplate>
      <DataTemplate>
       <TextBlock x:Name="WordWrap" Text="{Binding Name}" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"></TextBlock>
      </DataTemplate>
     </GridViewColumn.CellTemplate>
    </GridViewColumn>
 </Listview.View>
</Listview> 

I have a seperate overrides file with styles in it, that is setting other control template triggers and data triggers and here is what I tried there:

<Style.Triggers>
  <DataTrigger Binding="{Binding IsSelected, ElementName=WordWrap}" Value="True">
   <Setter Property="TextWrapping" Value="Wrap" />
  </DataTrigger>
 </Style.Triggers>
</Gridview>

I get this error: The member "TextWrapping" is not recognized or accessible.

Let me know any solutions or fixes please! Still very new to xaml and WPF.


Solution

  • TextBlock controls do not have an IsSelected property so your DataTrigger will never happen as is. IsSelected is a property on the containing ListViewItem so you can change your Trigger binding to that using RelativeSource. For Example:

    <TextBlock x:Name="WordWrap" Text="{Binding}" TextTrimming="CharacterEllipsis">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="TextWrapping" Value="NoWrap"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" Value="True">
                        <Setter Property="TextWrapping" Value="Wrap"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    

    Also, in order to change a property in a trigger, it cannot be hard coded in the element properties so move the original TextWrapping to within the Style as well.