我需要使用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