2017-08-03 23 views
-3

我在我的WPF中有一個datagrid視圖。我在那裏映射一個項目源.Dagagrid視圖包含所有行中的複選框。用戶可以選中或取消選中某些行。因此,我想遍歷數據網格行和單元格值來知道所選的行。我嘗試了所有在互聯網上的東西,但沒有什麼幫助。請幫助我解決我的問題如何遍歷WPF中的Datagrid?

+0

獲得幫助的最佳方式是提供一些代碼。像你目前沒有工作的進展。您可以輕鬆獲取選定的項目'dataGrid.selectedItems'。但進一步的信息會幫助我們幫助你...例如:你想在哪裏獲得選擇?你的架構是什麼樣的?希望您在CodeBehind或XAML中有選擇嗎?... – Jodn

回答

-1

從閱讀有關MVVM模式開始。

您需要一個模型。這應該實現INotifyPropertyChanged接口。並且每個屬性設置器應該調用OnPropertyChanged()方法。實施我留給你。

public class Model 
{ 
    public string Name { get; set; } 
    public bool IsChecked { get; set; } 
} 

您需要視圖模型。

public class ViewModel 
{ 
    public ObservableCollection<Model> MyList { get; set; } 

    public ViewModel() 
    { 
     MyList = new ObservableCollection<Model>(); 
     MyList.Add(new Model() { Name = "John", IsChecked = true }); 
     MyList.Add(new Model() { Name = "Bety", IsChecked = false }); 
     MyList.Add(new Model() { Name = "Samuel", IsChecked = true }); 
    } 
} 

並在視圖中的權利綁定。

<Window x:Class="WpfApp4.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:WpfApp4" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.DataContext> 
    <local:ViewModel></local:ViewModel> 
</Window.DataContext> 
<Grid> 
    <DataGrid ItemsSource="{Binding MyList}" AutoGenerateColumns="False" CanUserAddRows="False"> 
     <DataGrid.Columns> 
      <DataGridTextColumn Header="Description" Binding="{Binding Name}"/> 
      <DataGridCheckBoxColumn Header="Select" Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}"/> 
     </DataGrid.Columns> 
    </DataGrid> 
</Grid> 

然後你迭代在視圖模型的MYLIST,做你想要選中/未選中項目要做什麼。