我正在创建一个 CheckedComboBox WPF 控件。我想添加一个可以通过 XAML 绑定的 SelectedValuesProperty。我已经尝试了一些不同的东西,但还不能让它工作。有没有人对如何解决这个问题有任何建议?我的控件继承自 MultiSelector。提前致谢!
这是我到目前为止所拥有的,问题是我无法从对象中获取 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;
}
}
}