c# - 在 ListBox 中实现 Selectable 用户控件
问题描述
我有显示实体数据的小部件。我制作了用户控件来显示每个实体的数据。
<UserControl x:Class="Widget"
<Border BorderBrush="#FF000000" CornerRadius="10" Width="220" Height="180">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="BorderThickness" Value="5"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsSelected}" Value="False">
<Setter Property="BorderThickness" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel Orientation="Vertical">
<Label>Name</Label>
</StackPanel>
</Border>
</UserControl>
和背后的代码
public partial class Widget: UserControl
{
/// <summary>
/// Is Selected Dependency property
/// </summary>
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(StationStatus), new PropertyMetadata(false));
public bool IsSelected
{
get
{
return (bool)GetValue(IsSelectedProperty);
}
set
{
SetValue(IsSelectedProperty, value);
}
}
public Widget()
{
InitializeComponent();
}
}
用户控件在 ListBox 中呈现
<ListBox ItemsSource="{Binding WidgetData}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Single">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Grid.Row="0" ItemHeight="200" ItemWidth="230" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<view:StationStatus IsSelected="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected}">
</view:StationStatus>
</view:Widget>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我期望IsSelected
将ListBoxItem
其绑定到用户控制,并且在Listbox
选择该项目但无法正常工作时,边框厚度会改变。
解决方案
我没有足够的声誉来发表评论,所以我会把它放在答案中。
过去我遇到过类似的问题,我错误地捕获了 ListBox 事件并认为它应该应用于我在 ListBox 中的控件。好吧,它没有。在您的情况下,Widget 本身并没有真正被选中,并且您将边框绑定到 Widget 的属性,因此没有任何反应。或者至少在我看来是这样的。
推荐阅读
- sql-server - 从开始时间获取每小时数据
- css - WordPress(标题/导航栏)上同一图像的不同背景位置以及如何使它们相同?
- javascript - javascript innerhtml 显示为文本
- python - 如何在目录中的多个文件名中查找和替换两个不同的字符串?
- sql - 动态 SQL 转换文本和图像
- syntax - <> 在飞镖类扩展后的含义
- javascript - 停止 Axios 承诺链
- javascript - 用输出参数包装一个 c++ 函数,以便在 javascript/node 中使用
- woocommerce - 产品页面中的 Woo Commerce 产品图片太大。
- hibernate - JPA,休眠find()方法返回null