简体   繁体   English

将DataGrid动态添加到视图(MVVM)

[英]Adding DataGrid Dynamically to a View (MVVM)

I am trying to implement dynamic creation/removal of DataGrids. 我正在尝试实现DataGrids的动态创建/删除。 I want to achieve that a entire DataGrid is added or removed from the view when a certain property changes. 我想实现在某些属性更改时,在视图中添加或删除整个DataGrid。 My View constructor looks like this: 我的View构造函数如下所示:

public Document(){
        InitializeComponent();
        ViewModel = new DocumentViewModel();
        ViewModel.PropertyChanged += (sender, e) => { Test2(); };
        Test();

    }

private void Test()
    {
        _grid = new DataGrid();
        _grid.Height = 100;
        _grid.Width = 100;


        DataGridTextColumn column = new DataGridTextColumn();
        column.Header = "test";
        _grid.Columns.Add(column);
        _panel.Children.Add(_grid);
        content.Children.Add(_panel);

    }

This is the corresponding XAML code: 这是相应的XAML代码:

     <UserControl ... >      

        <Grid Name="content"> 

        </Grid> 
</UserControl>

So, the method "Test2" is executed when a property changes in the ViewModel. 因此,当ViewModel中的属性更改时,将执行方法“ Test2”。 I tried to add another grid in that method like this: 我试图在这种方法中添加另一个网格,如下所示:

  private void Test2()
    {
        DataGrid grid2 = new DataGrid();
        grid2.Height = 100;
        grid2.Width = 100;
        ((StackPanel) content.Children[0]).Children.Add(grid2); 
        content.UpdateLayout(); 
    }

but that does not work. 但这不起作用。 Also, if I do not call the "Test" method from the constructor but when a property is changed, nothing is created. 另外,如果我没有从构造函数中调用“ Test”方法,但是当更改属性时,则不会创建任何内容。 What am I doing wrong? 我究竟做错了什么?

Your code should work. 您的代码应该可以工作。 Check whether the PropertyChanged event is fired (and whether the Test() method is called before the event is fired). 检查是否触发了PropertyChanged事件(以及是否在触发事件之前调用了Test()方法)。

Check the size of your StackPanel - the second DataGrid maybe added, but can not be displayed because the StackPanel is not enough wide or high. 检查您的StackPanel的大小-可能添加了第二个DataGrid,但由于StackPanel的宽度或高度不够而无法显示。

Like HighCore and others suggested, I ended up using ItemsControl and binding it to a collection of DataTables. 像HighCore和其他建议的一样,我最终使用ItemsControl并将其绑定到DataTables的集合。 This works in this particular case, however, I can not dynamically create custom columns (eg have one column contain only string values and another one combo box) which I was hoping to achieve. 在这种特殊情况下,这是可行的,但是,我无法动态创建希望实现的自定义列(例如,一个列仅包含字符串值,而另一个包含组合框)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM