【发布时间】:2014-06-25 20:10:27
【问题描述】:
我有一个包含项目的 ListView,其中包含字符串字段 Name 等。 ListView 中的项目按此字段排序:
SortDescription descr = new SortDescription("Name", ListSortDirection.Ascending);
list.Items.SortDescriptions.Add(descr);
我还有一个 TextBlock,我想在其中显示已排序 ListView 中第一项的名称。可以在运行时添加、删除和编辑项目,所以我想使用某种绑定,如下所示(不起作用,仅作为示例):
<TextBlock Text="{Binding ElementName=list, Path=Items[0].Name}"/>
1) 如何使用绑定实现所需的行为?
2) 如果无法创建这样的绑定,那么成功的最方便的方法是什么?
任何想法和提示将不胜感激。
更新
主窗口内容:
<StackPanel>
<TextBlock Name="nameFirst" Text="{Binding ElementName=list, Path=Items[0].Name}"/>
<ListView Name="list" ItemsSource="{Binding ElementName=mainWnd, Path=List}" DisplayMemberPath="Name" Loaded="list_Loaded"/>
</StackPanel>
后面的代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public class Item : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public Item(string name)
{
Name = name;
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public ObservableCollection<Item> _list;
public ObservableCollection<Item> List
{
get { return _list; }
set
{
_list = value;
OnPropertyChanged("List");
}
}
public MainWindow()
{
InitializeComponent();
List = new ObservableCollection<Item>();
List.Add(new Item("1"));
List.Add(new Item("2"));
List.Add(new Item("3"));
}
private void list_Loaded(object sender, RoutedEventArgs e)
{
SortDescription descr = new SortDescription("Name", ListSortDirection.Descending);
list.Items.SortDescriptions.Add(descr);
}
}
应用程序启动时,ListView 中的项目按降序排列:“3”、“2”、“1”,但 nameFirst TextBox 仍显示“1”,但现在应该显示“3”。
【问题讨论】:
标签: wpf listview sorting binding