WPF - 如何使用MVVM将ICollectionView绑定到datagrids

时间:2016-04-27 20:03:57

标签: c# wpf mvvm datagrid icollectionview

我是WPF的新手,并按照此链接使用代码优先方法来构建示例。这个例子有效。 https://msdn.microsoft.com/en-us/data/jj574514.aspx

现在,我正在尝试将其更改为关注MVVM。

这是MainWindow XAML

<Window
    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:WPFwithEFSampleCodeFirst" mc:Ignorable="d" x:Class="WPFwithEFSampleCodeFirst.MainWindow"
    Title="MainWindow" Height="352.134" Width="517.53" Loaded="Window_Loaded">

<Grid  Margin="0,0,0,-3">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0*"/>
        <ColumnDefinition Width="77*"/>
        <ColumnDefinition Width="25*"/>
    </Grid.ColumnDefinitions>
    <Button Content="Save" Grid.Column="2" HorizontalAlignment="Left" Margin="41,167,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    <DataGrid Grid.ColumnSpan="2"  ItemsSource="{Binding Categories}" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="32,10,0,0" VerticalAlignment="Top" Height="124" Width="330" >
        <DataGrid.Columns>
            <DataGridTextColumn  Width="SizeToHeader" Header="Category Id" Binding="{Binding Path = CategoryId}"/>
            <DataGridTextColumn  Width="SizeToHeader" Header="Name" Binding="{Binding Path = Name}"/>
        </DataGrid.Columns>
    </DataGrid>

    <DataGrid Grid.ColumnSpan="2" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="32,153,0,0" VerticalAlignment="Top" Height="146" Width="330">
        <DataGrid.Columns>
            <DataGridTextColumn  Binding="{Binding CategoryId}" Header="Category Id" Width="SizeToHeader"/>
            <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
            <DataGridTextColumn  Binding="{Binding ProductId}" Header="Product Id" Width="SizeToHeader"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

这是MainWindowViewModel

 class MainWindowViewModel
{
    private ICollectionView _categoryView;

    public ICollectionView Categories
    {
        get { return _categoryView; }
    }

    ProductContext context = new ProductContext();

    public MainWindowViewModel()
    {
        IList<Category> categories = GetCategories();
        _categoryView = CollectionViewSource.GetDefaultView(categories);

    }

    public IList<Category> GetCategories()
    {
        return context.Categories.ToList();
    }
}

我不知道如何将第二个详细信息datagrid绑定到ViewModel。我想拥有与原始示例相同的Master-Details显示功能。

那么如何将Categories中的Products绑定到第二个datagrid呢?使用MVVM实现它的正确方法是什么?

更多信息:

 public class Category
{
    public Category()
    {
        this.Products = new ObservableCollection<Product>();
    }

    public int CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ObservableCollection<Product> Products { get; private set; }
} 

    public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
} 

    public class ProductContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
} 

3 个答案:

答案 0 :(得分:0)

最简单的方法是将详细DataGrid的DataContext绑定到主DataGrid的SelectedItem属性

<DataGrid x:Name="MasterGrid" Grid.ColumnSpan="2" ItemsSource="{Binding Categories}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn  Width="SizeToHeader" Header="Category Id" Binding="{Binding Path = CategoryId}"/>
        <DataGridTextColumn  Width="SizeToHeader" Header="Name" Binding="{Binding Path = Name}"/>
    </DataGrid.Columns>
</DataGrid>

<DataGrid DataContext="{Binding SelectedItem.Products, ElementName=MasterGrid}" Grid.ColumnSpan="2" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn  Binding="{Binding CategoryId}" Header="Category Id" Width="SizeToHeader"/>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
        <DataGridTextColumn  Binding="{Binding ProductId}" Header="Product Id" Width="SizeToHeader"/>
    </DataGrid.Columns>
</DataGrid>

答案 1 :(得分:0)

将主DataGrid的SelectedItem属性绑定到ViewModel

中的属性
<DataGrid SelectedItem="{Binding SelectedCategory}" Grid.ColumnSpan="2" ItemsSource="{Binding Categories}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn  Width="SizeToHeader" Header="Category Id" Binding="{Binding Path = CategoryId}"/>
        <DataGridTextColumn  Width="SizeToHeader" Header="Name" Binding="{Binding Path = Name}"/>
    </DataGrid.Columns>
</DataGrid>

MainWindowViewModel

private Category _selectedCategory;

public Category SelectedCategory
{
    get { return _selectedCategory; }
    set
    {
        _selectedCategory = value;
        OnPropertyChanged("SelectedCategory");
        OnPropertyChanged("SelectedCategoryProducts");
    }
}

(这需要您的视图模型实现INotifyPropertyChanged.OnPropertyChanged方法调用PropertyChanged事件处理程序)

添加另一个返回所选类别的产品属性的属性

public ObservableCollection<Product> SelectedCategoryProducts
{
    get
    {
        if (_selectedCategory == null) return null;

        return _selectedCategory.Products;
    }
}

将详细信息DataGrid绑定到视图模型中的SelectedCategoryProducts属性

<DataGrid ItemsSource="{Binding SelectedCategoryProducts}" Grid.ColumnSpan="2" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn  Binding="{Binding CategoryId}" Header="Category Id" Width="SizeToHeader"/>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
        <DataGridTextColumn  Binding="{Binding ProductId}" Header="Product Id" Width="SizeToHeader"/>
    </DataGrid.Columns>
</DataGrid>

答案 2 :(得分:0)

使用ICollectionView,不使用其功能将是一种耻辱......

首先,在您的第一个数据网格(类别)上设置IsSynchronizedToCurrentItem="true"

然后在第二个DataGrid中,将DataSource与ItemsSource="{Binding Categories.CurrentItem.Products}"绑定,其中Categories是您的视图模型ICollectionView

IsSynchToCurrentItem=true的效果是,您无需在视图模型中保留属性即可跟踪当前项目,因为ICollectionView会为您执行此操作。

然后,每次用户在数据网格中选择一行时,currentitem将在viewmodel中更改(并且ICollectionView上有一个事件通知),每次你在你的设置中设置当前项目视图模型,将选择相应的行。

除了此功能之外,ICollectionView还可以对您进行排序,过滤和分组,而无需触及您的源集合。最重要的是,它使您能够以编程方式更改当前项目在您查看模型中而无需在XAML CONTROL (以及相应的visual / XAML项目控件中的选定行),使用MoveCurrentTo(object target)MovecurrentToFirst()等方法....

您的业务C#模型很好,所以您的XAML看起来像这样:

<DataGrid Grid.ColumnSpan="2" IsSynchronizedToCurrentItem="true"  ItemsSource="{Binding Categories}" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="32,10,0,0" VerticalAlignment="Top" Height="124" Width="330" >
    <DataGrid.Columns>
        <DataGridTextColumn  Width="SizeToHeader" Header="Category Id" Binding="{Binding Path = CategoryId}"/>
        <DataGridTextColumn  Width="SizeToHeader" Header="Name" Binding="{Binding Path = Name}"/>
    </DataGrid.Columns>
</DataGrid>

<DataGrid Grid.ColumnSpan="2" ItemsSource="{Binding Categories.CurrentItem.Products}" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="32,153,0,0" VerticalAlignment="Top" Height="146" Width="330">
    <DataGrid.Columns>
        <DataGridTextColumn  Binding="{Binding CategoryId}" Header="Category Id" Width="SizeToHeader"/>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
        <DataGridTextColumn  Binding="{Binding ProductId}" Header="Product Id" Width="SizeToHeader"/>
    </DataGrid.Columns>
</DataGrid>