简体   繁体   中英

How to Bind entire datagrid to view MVVM following the MVVM pattern

I want to dynamically display data in form a of a table. The control I chose for different reasons is a DataGrid . That solution worked to a certain point, but when I needed to dyanmically alter which properties I wanted to display in the datagrid I encountered problems. When I bind its ItemsSource directly to an observable it shows all properties in the specific object, which I dont want. I want to Create a datagrid programatically and push it into the view somehow. Is that even possible?

I've been looking now for a long time but I can't seem to find a good solution. It's also important that the solution follows the MVVM-pattern.

public class MyViewModel 
{
    public Datagrid dataGrid = null;
    public MyObject gridObject = null;

    public MyViewModel () 
    {
           gridObject = new MyObject();
           dataGrid = CreateDataGrid(gridObject);
    }

    private Datagrid CreateDataGrid(object objectName) {}
}

After this I want to bind the grid to the XAML. Is it possible or is there a better way of doing this, rather then a DataGrid ? I want the functionality built into the datagrid like moving columns, mark specific rows etc..

You shouldn't create a DataGrid in a view model. This is no MVVM. You create it in the view.

If you don't want the DataGrid to autogenerate the columns for you, you should set its AutoGenerateColumns property to false .

You could then define the columns you want yourself, either in the XAML markup:

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="..." Binding="{Binding Property}" />
    </DataGrid.Columns>
</DataGrid>

Or programmatically:

dataGrid.Columns.Add(new DataGridTextColumn() { Header = "header...", Binding = new Binding("Property") });

The view model should return an IEnumerable<T> from a public property that the DataGrid in the view binds to:

<DataGrid ItemsSource="{Binding ViewModelCollection}" ...

Make sure that you set the DataContext of the view to an instance of the view model for the binding to work:

public MainWindow()
{
    InitializeComponent();
    DataContext = new ViewModel();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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