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 から独立しています。変更通知がある限り、UI はプロパティを更新し、プロパティは UI に影響を与えます。
[上記のコードは疑似コードとして扱います。現在、開発マシンを使用していません]