WPF比WinForms更具数据驱动力。这意味着处理对象(表示数据)比处理UI元素更好。
您应该有一个集合,它是数据网格的项目源。在相同的数据上下文中,您应该拥有一个将保存选定项目的属性(与集合中的项目类型相同)。所有属性都应通知更改。
考虑到你有MyItem
类在数据网格的每一行,该代码将是这样的:
在那是你的数据网格的数据上下文类:
public ObservableCollection<MyItem> MyCollection {get; set;}
public MyItem MySelectedItem {get; set;} //Add change notification
private string _myComparisonString;
public string MyComparisonString
{
get{return _myComparisonString;}
set
{
if _myComparisonString.Equals(value) return;
//Do change notification here
UpdateSelection();
}
}
.......
private void UpdateSelection()
{
MyItem theSelectedOne = null;
//Do some logic to find the item that you need to select
//this foreach is not efficient, just for demonstration
foreach (item in MyCollection)
{
if (theSelectedOne == null && item.SomeStringProperty.StartsWith(MyComparisonString))
{
theSelectedOne = item;
}
}
MySelectedItem = theSelectedOne;
}
在你XAML,您将拥有一个TextBox和一个DataGrid,与此类似:
<TextBox Text="{Binding MyComparisonString, UpdateSourceTrigger=PropertyChanged}"/>
....
<DataGrid ItemsSource="{Binding MyCollection}"
SelectedItem="{Binding MySelectedItem}"/>
这样,您的逻辑就与您的UI无关。只要你有更改通知 - 用户界面将更新属性,属性将影响用户界面。
[将上面的代码视为伪代码,我目前不在我的开发机器上]