【发布时间】:2022-01-02 01:41:38
【问题描述】:
我有一个 WPF 用户控件,它是一个包含 CheckBoxes 的 ListBox。
<UserControl x:Class="AC.CodA.WPF.UserControls.CheckedListBox"
x:Name="Root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:Background="White">
<StackPanel>
<ListBox BorderThickness="0"
ItemsSource="{Binding ElementName=Root, Path=ItemsSource}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable"
Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}"
Content="{Binding Item}">
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Separator />
<CheckBox x:Name="DeSelectAll"
Content="Select / deselect all"
Checked="DeSelectAll_Checked"
Unchecked="DeSelectAll_Unchecked" />
</StackPanel>
</UserControl>
我在另一个地方使用这个控件:
<GroupBox Header="{Binding ElementName=Root, Path=Header, FallbackValue=Header}">
<user:CheckedListBox ItemsSource="{Binding ElementName=Root, Path=Companies}" />
</GroupBox>
在这个地方,Companies 属性是一个ObservableCollection<CheckedListBoxItem<Company>>。
CheckedListBoxItem 是一个具有bool IsChecked 属性和通用T Item 属性的类。
现在,T Item 可以是任何东西。此时我将此属性设置为CheckBox 的Content,但大多数情况下这会导致类似AC.CodA.Scripting.Shared.Company 的模棱两可。
有没有办法在用户控件之外设置CheckBox Content?像CheckBoxContent这样的东西:
<GroupBox Header="{Binding ElementName=Root, Path=Header, FallbackValue=Header}">
<user:CheckedListBox ItemsSource="{Binding ElementName=Root, Path=Companies}" CheckBoxContent="{Binding Item.Name}" />
</GroupBox>
在我的对象内部:
<CheckBox IsChecked="{Binding IsChecked}"
Content="{Binding CheckBoxContent}">
</CheckBox>
【问题讨论】: