MVVM - How to create runtime columns for xamdatagrid?

I need to create an XamDataGrid that shows the dynamic number of columns for a time frame from x to y. Therefore, I do not know how many years the user will choose to have these columns created in advance.

Now, as a rule, in MVVM you simply fill in the data through as many properties as you need in the columns inside your XamDataGrid, and the latter simply generate their auto-generation.

Obviously, I couldn't just create properties in my ViewModel at runtime unless I did something crazy with Reflection.

How else could I achieve this?

Should I just create unrelated fields for the datagrid and populate them through code? I agree that at this point I won’t need two-way snapping because the grid is read-only ... just thinking out loud.

Is this approach OK without breaking the MVVM pattern? Thanks

+5
source share
2 answers

You can use indexes:

In your ViewModel:

public MyVariableCollection RowData
{
    get { return new MyVariableCollection(this); }
}

In MyVariableCollection: protected SomeRowViewModel viewModel;

public MyVariableCollection(SomeRowViewModel viewmodel)
{
    this.viewModel = viewmodel;
}

public object this[string name]
{
    get { return viewModel.GetRowColumnValue(name); }
}

I tried to save it briefly: but the idea is that you have a new class with an index defined, then you can link like this:

{Binding Path=SomeRowViewModelInstance.RowData["ColumnName"]}

- ; .

, - , , .


: ComponentModel TypeDescriptor. , "" . , , , , .

+4

, .

, datagrid xam DataSource (.. ).

, ( PropertyChanged FieldLayoutInitializing ), , :

private void ReRenderGrid()
{
    XamDataGrid.FieldLayouts.Clear();
    XamDataGrid.ClearValue(DataPresenterBase.DataSourceProperty);
    XamDataGrid.DataSource = DataSource.Data.DefaultView;
}

, xamdatagrid , reset:

XamDataGrid.FieldLayoutInitializing += LayoutInitializing;

Handler:

private void LayoutInitializing(object sender, FieldLayoutInitializingEventArgs e)
{
    const string deletebuttonstyle = "DeleteButtonStyle";
    const string requiredinputvalue = "RequiredInputValue";
    const string optionalinputvalue = "OptionalInputValue";
    const string outputvalue = "OutputValue";

    var fieldLayout = e.FieldLayout;
    fieldLayout.Fields.Clear();

    AddFields(DataSource.InColumns, requiredinputvalue, fieldLayout);
    AddSplitter(fieldLayout);
    AddFields(DataSource.OptionalInColumns, optionalinputvalue, fieldLayout);
    AddSplitter(fieldLayout);
    AddFields(DataSource.OutColumns, outputvalue, fieldLayout);

    AddUnboundField(fieldLayout, string.Empty, GetStyle(deletebuttonstyle));
}

, . AddFields :

private void AddField(string name, Style style, FieldLayout fieldLayout)
{
    var field = new Field {Name = name};
    field.Settings.LabelPresenterStyle = style;
    field.Settings.CellValuePresenterStyle = GetStyle("StandardCellValueStyle");
    fieldLayout.Fields.Add(field);
}

AddSplitter AddUnboundField .

+1

All Articles