Good day. My question is how best to make dynamically-created controls on MVVM, that is, how best to design a UI interface? enter image description here

  • Do you really need dynamic , runtime created controls? Describe your real task. - VladD
  • Well, in fact, I would like to make a parody of the unreal engine blueprint, but for quite other purposes, but with a similar in principle to the interface (here's a video of youtu.be/kmnC6IUPGjI ). This is not to explain for a long time and not to confuse. - alex-rudenkiy
  • Uh, any explanation will be shorter than 13 minutes of video. And the question is not the technical side, the appearing-disappearing buttons can be done in hundreds of different ways. The question is what kind of entity you want to show the user. From this and only on this depends which way is correct. - VladD
  • Is it possible to write something like hp? :) - alex-rudenkiy 1:21 pm
  • How is this "essence"? - alex-rudenkiy

1 answer 1

For example, like this:

<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:WpfApp2.ViewModel" mc:Ignorable="d" Title="MainWindow"> <Window.DataContext> <vm:MainViewModel/> </Window.DataContext> <Window.Resources> <DataTemplate DataType="{x:Type vm:ListViewModel}"> <ListBox ItemsSource="{Binding Items}"/> </DataTemplate> <DataTemplate DataType="{x:Type vm:TextViewModel}"> <TextBlock Text="{Binding Text}"/> </DataTemplate> <DataTemplate DataType="{x:Type vm:ButtonViewModel}"> <Button Content="{Binding Caption}"/> </DataTemplate> </Window.Resources> <Grid> <ContentControl Content="{Binding Content}"/> </Grid> </Window> 

Where presentation models are as follows:

 class MainViewModel { public MainViewModel() { Content = new ListViewModel ( new TextViewModel() { Text = "НаТми ΠΊΠ½ΠΎΠΏΠΊΡƒ" }, new ButtonViewModel() { Caption = "Π–ΠΌΠ°ΠΊΠ½ΠΈ мСня" } ); } public object Content { get; } } class ListViewModel { public ListViewModel(params object[] items) { Items = items; } public IEnumerable<object> Items { get; } } class TextViewModel { public string Text { get; set; } } class ButtonViewModel { public string Caption { get; set; } } 

PS: Just keep in mind that the generation of a view is a rather slow operation. And if you plan on the fly to generate and modify complex interfaces - you get the brakes. It is more profitable to generate once for all occasions, and just hide the unnecessary.