views:

134

answers:

0

I'm working on creating a CheckedComboBox WPF control. I want to add a SelectedValuesProperty that I could bind through via XAML. I've tried a few different things and haven't been able to get it to work yet. Does anyone have any suggestions on how to approach this? My control inherits from MultiSelector. Thanks in advance!

This is what I have so far, problem is I can't get the itemcontainer from the object:

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;
    }
  }
}