Home > Net >  How to bind Enum to Text property of TextBlock in ListBox
How to bind Enum to Text property of TextBlock in ListBox

Time:01-11

I am not successful at getting my DataTrigger to work for binding to enum.
Each line in the ListBox is 'S', just as in the default Setter
XAML:

<Window x:Class="BindToEnumTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BindToEnumTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox Grid.Column="0" x:Name="LBMain" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Auto">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Grid.Column="0" x:Name="TxtType">
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Setter Property="Text" Value="S" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding Type}" Value="TypeEnum.User">
                                        <Setter Property="Text" Value="U"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


Code:

namespace BindToEnumTest
{
    public enum TypeEnum { None, System, User }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public Collection<TypeEnum> TypeList = new() { TypeEnum.System, TypeEnum.User, TypeEnum.System, TypeEnum.User };

        public MainWindow()
        {
            InitializeComponent();

            LBMain.DataContext = TypeList;
        }
    }
}

I have tried using 'TypeEnum.User' and 'User' in the DataTrigger - no help.
Using Text="{Binding}" in the TextBlock shows 'User' and 'System' in the ListBox, so it seems to be getting the data.
How can I change this trigger to function?

CodePudding user response:

A TypeEnum instance has no Type property, hence the Binding must not specify a property path:

<DataTrigger Binding="{Binding}" Value="{x:Static local:TypeEnum.User}">

Or with built-in type conversion from string to enum:

<DataTrigger Binding="{Binding}" Value="User">
  • Related