【问题标题】:WPF ListBox DataTrigger does not fireWPF ListBox DataTrigger 不会触发
【发布时间】:2013-03-16 00:35:21
【问题描述】:

我有一个“播放列表”,我想强调“正在播放”项。

我试过了

<!-- Row 5: Playlist -->
    <ListBox x:Name="Tracks" MinHeight="400" Grid.Row="5" Margin="20">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel Height="44" Width="436" Dock="Left">
                    <StackPanel Orientation="Vertical" Width="374" Name="Wrapper">
                        <Label Content="{Binding Path=title}"  Name="Test" Foreground="CornflowerBlue" FontSize="14" Padding="0" />
                        <Label Content="{Binding Path=artist}" Foreground="DarkGray"       FontSize="14" Padding="0" />
                    </StackPanel>
                    <Label Content="{Binding Path=DurationFormatted}" Foreground="DarkGray" Width="62" Padding="0" DockPanel.Dock="Right" HorizontalContentAlignment="Right" />
                </DockPanel>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Path=NowPlaying}" Value="True">
                        <Setter TargetName="Wrapper" Property="Background" Value="LightBlue"/>
                        <Setter TargetName="Test" Property="FontSize" Value="24"/>
                        <Setter Property="ListBoxItem.Foreground" Value="Red" />
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

还有这个

<ListBox.ItemTemplate>
same stuff without Triggers section
<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
       <Style.Triggers>
           <DataTrigger Binding="{Binding Path=NowPlaying}" Value="True">
              <Setter Property="ListBoxItem.Background"  Value="Red" />
           </DataTrigger>
       </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

NowPlaying 只是音频模型的布尔属性,我在调试器中检查了当前对象确实得到了 NowPlaying == true。但是这两个触发器都不会改变项目的外观。我做错了什么? 另外,就我而言,我更喜欢命令式风格。从代码隐藏中做到这一点很容易吗?

附:我为强调的项目设置了极值只是为了测试:)

【问题讨论】:

    标签: wpf listbox datatrigger


    【解决方案1】:

    还记得您需要通过实现INotifyPropertyChanged 接口来提高NowPlaying 属性吗?否则,绑定引擎无法看到属性已更改,因此无法对视图进行更新。

    还有一点点补充:我肯定会赞成第一种方法,尽量避免使用datatrigger,实际上所有与业务数据相关的数据绑定都尽可能采用样式。 Style 应该只包含视图设计,DataTemplates 用于显示真实数据。如果您将其分开,则更容易重用样式。

    【讨论】:

    • 谢谢,我不知道 INotifyPropertyChanged。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2021-11-28
    • 1970-01-01
    • 2014-07-08
    • 2010-12-10
    相关资源
    最近更新 更多