首页 > 解决方案 > 在 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>

我期望IsSelectedListBoxItem其绑定到用户控制,并且在Listbox选择该项目但无法正常工作时,边框厚度会改变。

标签: c#wpflistboxuser-controls

解决方案


我没有足够的声誉来发表评论,所以我会把它放在答案中。

过去我遇到过类似的问题,我错误地捕获了 ListBox 事件并认为它应该应用于我在 ListBox 中的控件。好吧,它没有。在您的情况下,Widget 本身并没有真正被选中,并且您将边框绑定到 Widget 的属性,因此没有任何反应。或者至少在我看来是这样的。


推荐阅读