2017-08-03 83 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,做你想要选中/未选中项目要做什么。