WPF Datatrigger在预期时未触发

17 *_* 26 29 wpf datatrigger

我有以下XAML:

<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
                    <Setter Property="TextBlock.Text" Value="item selected"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

第一个文本块愉快地使用SelectedItems.Count更改,显示0,1,2等.第二个块上的数据触发器似乎永远不会触发更改文本.

有什么想法吗?

Rob*_*nee 28

或者,您可以用以下方法替换您的XAML:

<TextBlock Margin="0,0,5,0" Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}"/>
<TextBlock>
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Text" Value="items selected"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
                    <Setter Property="Text" Value="item selected"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

转换器可以解决许多绑定问题,但是有很多专用转换器会变得非常混乱.


Ala*_* Le 13

DataTrigger正在触发,但第二个TextBlock的Text字段被硬编码为"选中的项目",因此无法更改.要查看它,您可以删除Text ="items selected".

您的问题是使用ValueConverter而不是DataTrigger的理想选择.以下是如何创建和使用ValueConverter来将Text设置为您想要的内容.

创建此ValueConverter:

public class CountToSelectedTextConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((int)value == 1)
            return "item selected";
        else
            return "items selected";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

将命名空间引用添加到转换器所在的程序集:

xmlns:local="clr-namespace:ValueConverterExample"
Run Code Online (Sandbox Code Playgroud)

将转换器添加到您的资源:

<Window.Resources>
    <local:CountToSelectedTextConverter x:Key="CountToSelectedTextConverter"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

将您的第二个文本块更改为:

    <TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

  • 如果您需要数据触发器来控制情节提要怎么办?转换器不适合这种情况。有什么建议吗? (2认同)