[英]WPF: Custom ListBoxItem with CheckBox - Strike through text on Checked
我正在编写一个简单的待办事项列表,我有一个TaskItem类,其中包含属性“ Completed”,该类实现了在该类和所有属性上更改的inotifypropertychanged。
我需要的是能够设置DataTrigger,以便在选中/取消选中复选框时,文本会被删除。
我的列表框代码如下:
<ListBox x:Name="TaskListBox" Background="#FF515658" Cursor="Arrow">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Focusable" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<CheckBox Name="CheckBoxZone" Tag="{Binding ID}" IsChecked="{Binding Completed}" Margin="0 0 0 0" Grid.Column="0"/>
<TextBlock x:Name="TaskNameLabel" Text="{Binding Name}" Foreground="White" Margin="10 -1 0 0" Grid.Column="1"/>
<Image x:Name="DelTaskButtom" Margin="8 -1 10 0" Height="10px" Width="10px" Source="../Resources/Delete.png" Cursor="Hand" Grid.Column="2" Visibility="Hidden" PreviewMouseLeftButtonDown="TaskListBoxItem_DeleteTask"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource TemplatedParent}}" Value="True">
<Setter Property="Visibility" TargetName="DelTaskButtom" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsChecked,RelativeSource={RelativeSource AncestorType={x:Type CheckBox}}}" Value="True">
<Setter Property="TextBlock.TextDecorations" Value="Strikethrough" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
谁能帮我这个? 我可以通过XAML进行操作还是需要设置事件并通过代码的方式进行操作?
问题出在触发器中。 您不能在DataTemplate触发器中使用相对源。 另一个问题是塞特犬。 您必须指定TargetName。
有两种方法可以在DataTemplate中编写触发器:
使用DataTrigger:
<DataTrigger Binding="{Binding Completed}" Value="True">
<Setter TargetName="TaskNameLabel" Property="TextDecorations" Value="Strikethrough" />
</DataTrigger>
或使用触发器
<Trigger SourceName="CheckBoxZone" Property="IsChecked" Value="True">
<Setter TargetName="TaskNameLabel" Property="TextDecorations" Value="Strikethrough" />
</Trigger>
两种情况下的设置器都相同
您可以将触发器添加到textblock而不是整个数据模板:
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<!-- Here is how we bind to another control's property -->
<DataTrigger Binding="{Binding IsChecked, ElementName=CheckBoxZone}" Value="True">
<Setter Property="TextBlock.TextDecorations" Value="Strikethrough" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.