2013-10-17 35 views
0

我對WPF相當陌生,我正在和Bindings玩耍。我設法將綁定設置爲List以便顯示例如網格中的人員列表。我現在想要的是在綁定上設置一個條件,並且只從網格中選擇滿足這種條件的人。我至今是:如何設置綁定到列表的選擇條件?

// In MyGridView.xaml.cs 
public class Person 
{ 
    public string name; 
    public bool isHungry; 
} 

public partial class MyGridView: UserControl 
{ 
    List<Person> m_list; 
    public List<Person> People { get {return m_list;} set { m_list = value; } } 

    public MyGridView() { InitializeComponent(); } 
} 

// In MyGridView.xaml 

<UserControl x:Class="Project.MyGridView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Grid>  
     <DataGrid Name="m_myGrid" ItemsSource="{Binding People}" /> 
    </Grid> 
</UserControl> 

我現在想什麼,是隻在列表中包括Person情況下,誰是餓了。我知道一個辦法做到這一點的代碼,例如添加新的屬性:

public List<Person> HungryPeople 
{ 
    get 
    { 
     List<Person> hungryPeople = new List<Person>(); 
     foreach (Person person in People) 
      if (person.isHungry) 
       hungryPeople.Add(person); 
     return hungryPeople; 
    } 
} 

,然後更改綁定到HungryPeople代替。不過,我並不認爲這是一個很好的選擇,因爲它涉及到製造額外的公共財產,這可能不合意。有沒有辦法在XAML代碼中實現這一切?

+0

如果您想按需排序和過濾,您將需要實現自定義[集合視圖](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.icollectionview.aspx)。 – Will

回答

5

使用CollectionViewSource與過濾器:

結合:

<UserControl x:Class="Project.MyGridView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
<UserControl.Resources> 
    <CollectionViewSource x:key="PeopleView" Source="{Binding People} Filter="ShowOnlyHungryPeople" /> 
</UserControl.Resources> 
    <Grid>  
     <DataGrid Name="m_myGrid" ItemsSource="{Binding Source={StaticResource PeopleView}}" /> 
    </Grid> 
</UserControl> 

過濾器:

private void ShowOnlyHungryPeople(object sender, FilterEventArgs e) 
{ 
    Person person = e.Item as Person; 
    if (person != null) 
    { 
     e.Accepted = person.isHungry; 
    } 
    else e.Accepted = false; 
} 
+0

這是一個美麗的解決方案,工作!不幸的是,當MyGridView的'DataContext'發生變化時,整個事件就會崩潰。你怎麼可以將'Filter'綁定到明確的'MyGridView.ShowOnlyHungryPeople'? – Yellow

0

您不需要多個屬性,只需爲您的Person類創建一個ObservableCollection並綁定到DataGridItemsSource即可。

public ObservableCollection<Person> FilterPersons{get;set;} 

<DataGrid Name="m_myGrid" ItemsSource="{Binding FilterPersons}" /> 

在您查看的構造函數初始化這個集合與您People主列表。

在每個過濾器上(例如匈牙利,渴等)只需從FilterPersons添加/刪除Person,您的DataGrid將相應更新。

0

你可以做的是在你的綁定中使用Converter,並且你可以根據你的需要過濾List,並返回過濾後的List。

<DataGrid Name="m_myGrid" ItemsSource="{Binding People, Converter=myConverter}" /> 

和轉換器 -

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     List<Person> hungryPeople = new List<Person>(); 
     foreach (Person person in value as List<Person>) 
      if (person.isHungry) 
       hungryPeople.Add(person); 
     return hungryPeople; 
    } 
} 
相關問題