我需要使用ItemsSource和CheckedItems属性实现CheckBoxList控件。如果CheckedItems包含这些值,则ItemsSource中的项目应显示为已选中的复选框,否则将取消选中。此外,我需要对CheckedItems属性的双向数据绑定支持(此属性的值应在用户单击复选框时更新)。Silverlight中自定义CheckBoxList控件的CheckedItems属性
这里是一些代码,这可能有助于理解我的问题
XAML:
<UserControl x:Class="Namespace.Controls.CheckBoxList" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListBox x:Name="LayoutRoot">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UserControl>
后面的代码:
public partial class CheckBoxList : UserControl
{
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CheckBoxList), null);
public static readonly DependencyProperty CheckedItemsProperty = DependencyProperty.Register("CheckedItems", typeof(IEnumerable), typeof(CheckBoxList), null);
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public IEnumerable CheckedItems
{
get { return (IEnumerable)GetValue(CheckedItemsProperty); }
set { SetValue(CheckedItemsProperty, value); }
}
public CheckBoxList()
{
InitializeComponent();
LayoutRoot.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("ItemsSource") { Source = this });
}
}
我认为我需要绑定列表框自定义到用户控件转换器,它将返回具有额外的IsChecked属性的项目集合,但它仅适用于单向数据绑定的情况。
看起来我需要同时对两个属性进行双向绑定,但我不知道如何实现它,并且会很感谢这个问题的任何帮助。
在此先感谢。
非常感谢!如果我的想法正确无误(将复选框的状态映射到列表项的选择状态),则可以使用SelectedItems而不是CheckedItems。在这种情况下,我没有看到需要处理SelectionChanged事件。此外,我是Silverlight的新手,因此修改默认的ListBox风格对我来说并不重要:) – altso 2009-12-14 15:01:50
Ooops,SelectedItems不是依赖项属性。需要像你说的那样处理SelectionChanged。 – altso 2009-12-14 15:19:00
是的,你不能指定SelectedItems属性,所以你需要桥接ListBox的SelectedItems属性和你正在公开的新属性,它允许消费者设置一个IList来控制操作。一旦初始SelectedItems设置为分配给您的属性,您可以通过SelectionChanged事件保持两个列表同步。 – AnthonyWJones 2009-12-14 15:30:37