【问题标题】:equivalent code in wpfwpf中的等效代码
【发布时间】:2013-05-27 06:08:53
【问题描述】:

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

【问题讨论】:

    标签: wpf vb.net datagrid datagridview


    【解决方案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。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多