简体   繁体   中英

How to generate rows and columns of a grid in WPF MVVM without editing the view?

I understand that the idea behind MVVM is to separate the View from the Viewmodel and that code-behind in the View is a bad thing.

This is how I used to generate a specific number of columns when I didn't follow the MVVM (xaml.cs).

for (int i = 0; i < Constants.GRID_COLUMN_NUMBER; i++)
{
    ColumnDefinition tempColumn = new ColumnDefinition();
    gridName.ColumnDefinitions.Add(tempColumn);
}

Since accessing the grid from ViewModel to generate rows/columns is a bad thing, what would be the most efficient way to achieve this?

Would using a user-control with a code-behind be an acceptable solution?

You can use behaviors for that purpose. You don't have to add code behind to your View, you just create a dedicated class that is responsible for generating the grids as a Behavior<Grid> and you add it to your xaml.

The Behavior<Grid> can then also be put under unit test separately.

Microsoft Blend uses this approach.

eg

public class DynamicColumn: Behavior<Grid> {}

and you use it like this

<Grid>
   <Interaction.Behaviors>
      <DynamicColumn />
   </Interaction.Behaviors>
<Grid>

You can find more info here: https://www.wpftutorial.net/Behaviors.html

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