0

Winforms では、以下のコードを使用して DataGridView で特定の項目を選択しました。

If DGView.Rows(row).Cells(0).Value.StartsWith(txtBoxInDGView.Text, StringComparison.InvariantCultureIgnoreCase) Then
    DGView.Rows(row).Selected = True
    DGView.CurrentCell = DGView.SelectedCells(0)
End If

誰でも WPF DataGrid の同等のコードを提供できますか?

4

1 に答える 1

1

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 に影響を与えます。

[上記のコードは疑似コードとして扱います。現在、開発マシンを使用していません]

于 2013-05-27T21:24:29.357 に答える