2016-08-16 57 views
1

重复我有一个ObservableCollection<M> fooBar {get;set;}。类M.cs看起来是这样的:WPF隐藏与CollectionViewSource

public class M{ 
    private int _ID; 
    public int ID { 
     get {return this._ID;} 
     set {this._ID = value;} 
    } 

    private string _number; 
    public int Number { 
     get {return this._number;} 
     set {this._number = value;} 
    } 

    private string _power; 
    public int Power { 
     get {return this._power;} 
     set {this._power = value;} 
    } 

    /* 
     ... 
    */ 
} 

现在我想只隐藏属性格式Power的副本。在我的.xaml代码我写了这个:

<UserControl.Resources> 
    <CollectionViewSource x:Key="myCollection" Source="{Binding Path=fooBar}"> 
     <CollectionViewSource.GroupDescriptions> 
      <PropertyGroupDescription PropertyName="Power"/> 
     </CollectionViewSource.GroupDescriptions> 
    </CollectionViewSource> 
</UserControl.Resources> 

我这个集合绑定到我的ComboBox

<ComboBox Name="cbValues" 
    ItemsSource="{Binding Source={StaticResource myCollection}}" 
    DisplayMemberPath="{Binding Power}" 
    SelectedValuePath="{Binding Power}" 
    /> 

ComboBox填写正确的值,但仍有重复。我怎样才能隐藏它们?

+1

填写资料的收集 – Eldho

+0

尽可能避免重复数据WPF Combobox中的[Distinct Values]的副本(http://stackoverflow.com/questions/5995989/distinct-values-in-wpf-combobox) –

+0

@Eldho不同的机器可以拥有相同的电源。 – MyNewName

回答

1

你可以尝试CollectionViewSource.Filter

myCollection.Filter+= new FilterEventHandler(ShowOnlyDistinctFilter); 

此事件处理程序使用过滤和显示相关的数据源

private void ShowOnlyDistinctFilter(object sender, FilterEventArgs e) 
{ 
    var item= e.Item as M; 
    if (item != null) 
    { 
     //Your distinct logic here 
    } 
} 
+0

谢谢你的回答!我还有一个问题。显示的属性基于另一个“ComboBox”。因此,该属性可以是“Power”,“ID”或“Number”。你能解释一下你的代码吗? – MyNewName