2010-06-14 3 views
6

여기 collectionviewsource 정렬 속성 이름을 알려주는 xaml입니다.CollectionViewSource의 PropertyName 바인딩 Xaml의 SortDescription

<CollectionViewSource Source="{Binding Contacts}" x:Key="contactsCollection" Filter="CollectionViewSource_Filter"> 
      <CollectionViewSource.SortDescriptions> 
       <scm:SortDescription PropertyName="DisplayName" /> 
      </CollectionViewSource.SortDescriptions> 
</CollectionViewSource> 

XAML은 위의 잘 작동하지만이 문제는 SortDescription PROPERTYNAME에 변수 값을 제공하는 방법을 모른다는 것이다. 내 viewmodel에서 어떤 속성을 정렬할지 알려주지 만이 속성을 SortDescription의 PropertyName 필드에 바인딩 할 수없는 속성이 있습니다.

어떨까요?

답변

7

정렬 설명을 코드 뒤에 설정할 수 있습니다.

XAML : 뒤에

<Window.Resources> 

    <CollectionViewSource Source="{Binding People}" x:Key="_peopleCVS" /> 

</Window.Resources> 

<StackPanel> 
    <ListBox 
     ItemsSource="{Binding Source={StaticResource _peopleCVS}}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Path=Name}" Margin="5,0"/> 
        <TextBlock Text="{Binding Path=Age}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
    <ComboBox SelectionChanged="ComboBox_SelectionChanged"> 
     <ComboBoxItem>Age</ComboBoxItem> 
     <ComboBoxItem>Name</ComboBoxItem> 
    </ComboBox> 
</StackPanel> 

코드 :

using System.Collections.Generic; 
using System.ComponentModel; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Controls.Primitives; 
using System.Windows.Data; 

namespace CollectionViewSourceDemo 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 

      People = new List<Person>(); 
      People.Add(new Person("Bob", 34)); 
      People.Add(new Person("Sally", 12)); 
      People.Add(new Person("Joe", 56)); 
      People.Add(new Person("Mary", 23)); 

      DataContext = this; 
     } 

     public List<Person> People { get; private set; } 

     private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      ComboBoxItem comboBoxItem = (sender as Selector).SelectedItem as ComboBoxItem; 
      string sortProperty = comboBoxItem.Content as string; 
      CollectionViewSource cvs = FindResource("_peopleCVS") as CollectionViewSource; 
      cvs.SortDescriptions.Clear(); 
      cvs.SortDescriptions.Add(new SortDescription(sortProperty, ListSortDirection.Ascending)); 
     } 
    } 

    public class Person 
    { 
     public Person(string name, int age) 
     { 
      Name = name; 
      Age = age; 
     } 

     public string Name { get; private set; } 
     public int Age { get; private set; } 
    } 
} 
관련 문제