2013-05-27 187 views
0

在Winforms中,我使用下面的代碼來選擇DataGridView中的特定項目。wpf中的等效代碼

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

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無關。只要你有更改通知 - 用戶界面將更新屬性,屬性將影響用戶界面。

[將上面的代碼視爲僞代碼,我目前不在我的開發機器上]