wpf中的等效代码

时间:2013-05-27 06:08:54

标签: wpf vb.net datagrid datagridview

在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的等效代码吗?

1 个答案:

答案 0 :(得分: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。

[将上面的代码视为伪代码,我目前不在我的开发机器上]

相关问题