0
我正在創建一個CheckedComboBox WPF控件。我想添加一個可以通過XAML綁定的SelectedValuesProperty。我已經嘗試了一些不同的東西,但還沒有能夠完成它的工作。有沒有人有任何建議如何解決這個問題?我的控件繼承自MultiSelector。提前致謝!在WPF控件上實現SelectedValues屬性
這是我到目前爲止,問題是我無法從對象獲得itemcontainer:
public static readonly DependencyProperty SelectedValuesProperty = DependencyProperty.Register(
"SelectedValues", typeof(IEnumerable), typeof(CheckedComboBox),
new FrameworkPropertyMetadata((IEnumerable) null,
new PropertyChangedCallback(OnSelectedValuesChanged)));
private static void OnSelectedValuesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CheckedComboBox combo = (CheckedComboBox) d;
IEnumerable oldValue = (IEnumerable) e.OldValue;
IEnumerable newValue = (IEnumerable) e.NewValue;
// unselect all the old vlaues
if (oldValue != null)
{
foreach (object obj in oldValue)
{
CheckedComboBoxItem item = obj as CheckedComboBoxItem;
if (item == null)
item = combo.ItemContainerGenerator.ContainerFromItem(obj) as CheckedComboBoxItem;
if (item != null && item.IsEnabled && item.IsSelected)
item.IsSelected = false;
}
}
// select all the new values
if (e.NewValue != null)
{
foreach (object obj in newValue)
{
CheckedComboBoxItem item = obj as CheckedComboBoxItem;
if (item == null)
item = combo.ItemContainerGenerator.ContainerFromItem(obj) as CheckedComboBoxItem;
if (item != null && item.IsEnabled && !item.IsSelected)
item.IsSelected = true;
}
}
}