【问题标题】:Implement SelectedValues property on WPF control在 WPF 控件中实现 Selected Values 属性
【发布时间】:2009-06-04 01:05:28
【问题描述】:

我正在创建一个 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;
    }
  }
}

【问题讨论】:

    标签: wpf itemscontrol multi-select selectedvalue


    【解决方案1】:

    我正在尝试解决同样的问题。我需要一个 SelectedValues(不是 SelectedItems)与 SelectedValuePath 一起使用,这样如果我传入一个对象集合,我可以在这些对象上指定一个属性以使用返回的值。 SelectedValues 将返回值的集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 2014-08-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多