[英]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.我知道 MVVM 背后的想法是将View与Viewmodel分开,而View中的代码隐藏是一件坏事。
This is how I used to generate a specific number of columns when I didn't follow the MVVM (xaml.cs).这就是我在不遵循 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?由于从ViewModel访问网格以生成行/列是一件坏事,那么实现这一目标的最有效方法是什么?
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.您不必在视图中添加代码,只需创建一个专用的 class 负责将网格生成为
Behavior<Grid>
并将其添加到 xaml。
The Behavior<Grid>
can then also be put under unit test separately.然后
Behavior<Grid>
也可以单独进行单元测试。
Microsoft Blend uses this approach. Microsoft Blend 使用这种方法。
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您可以在此处找到更多信息: https://www.wpftutorial.net/Behaviors.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.