【问题标题】:How to keep SelectedIndex to -1 on ItemsSource change如何在 ItemsSource 更改时将 SelectedIndex 保持为 -1
【发布时间】:2014-02-21 15:37:10
【问题描述】:

我有一个这样的Combobox 设置:

<ComboBox ItemsSource={Binding FilteredGroups} Name="cbo"/>

每次FilteredGroups 对象更改时,SelectedIndex 变为 0,但我需要它变为 -1。我目前的解决方法如下,但我很好奇是否有更好的方法来做到这一点:

 ViewModel.OnPropertyChanged += (o,e) => 
    {
        if(e.PropertyName == "FilteredGroups")
            _resetAdd = true;
    }

 cboOnSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (_resetAdd && e.AddedItems.Count > 0)
         cbo.SelectedIndex = -1;
     else if(!_resetAdd && e.AddedItems.Count > 0)
      //Normal selection logic
     _resetAdd = false;
 }

我尝试在 XAML 中设置 SelectedIndex=-1,并绑定到我在组更改期间设置为 null 的 VM 上的对象。

我也在使用 ItemTemplate,如果这有影响的话?

【问题讨论】:

  • 这可能是 SelectedItem 在这里领先,并且您的 itemssource 中有一个实际项目为空。否则这是一个奇怪的问题。或者尝试将 selecteditem 设置为 null :)
  • 您是否尝试过在SelectedItem 属性上设置双向绑定,然后在更改FilteredGroups 集合时将绑定属性设置为null?
  • FilteredGroups 是什么类型的集合?
  • @Blam IEnumerable....我猜你建议我试试 ObservableCollection?
  • 不确定。过滤器的本质是什么?您是否有要过滤的静态列表或更多动态内容?

标签: c# .net wpf xaml .net-4.0


【解决方案1】:

您可以在更改任何DependencyProperty 时收听并从那里进行设置。

DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof (ComboBox)).AddValueChanged(cb, (s, e) => { cb.SelectedIndex = -1; });

并且不要忘记调用RemoveValueChanged 以避免内存泄漏。

【讨论】:

    猜你喜欢
    • 2013-05-20
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2018-03-17
    • 2013-05-13
    • 1970-01-01
    • 2018-07-27
    相关资源
    最近更新 更多