如何通过MVVM中的循环创建多个usercontrol实例 [英] How to create multiple instance of a usercontrol through a loop in MVVM
问题描述
您好,
我有一个窗口表单,我根据所选值从combobox.Now中选择一个值如果我有3个项目,则3次用户控件应显示文本框在每个用户控件中如何实现。如何在mvvm中创建相同用户控件的多个实例
Hello,
I have a window form in which i select a value from combobox.Now based on the selected value if i have 3 items for that 3 times a user control should be displayed with textboxes in each user control.How can i achieve creating multiple instance of same user control in mvvm
MAinWIndow.Xaml
<ItemsControl ItemsSource="{Binding Bindgrid}" Margin="26,277,281,136">
<itemscontrol.itemtemplate>
<DataTemplate DataType="{x:Type VM:MRRUserViewModel}">
<local:MMRUserControl />
here bindgrid is the observable collection which hold the value to be displayed in the user control textbox
VM:MRRUserViewModel it is the view model of usercontrol which calls the method that gives the result of bindgrid
我尝试过:
我只能显示一个用户控件实例
What I have tried:
I am able to show only one instance of User Control
推荐答案
使用ObservableCollection
保存要在多个UserControls
中显示的数据的模型或ViewModel。然后在 XAML 文件中,使用ItemsControl
(包含在ScrollViewer
控件中)或ListBox
并使用UserControl
设置DataTemple
。 />
更新:以下是根据要求为您提供的工作示例...
模型和ViewModel可能具有可以更改的属性。这是一个与INotifyPropertyChanged绑定接口一起使用的基类:
Use anObservableCollection
holding Models or ViewModels of the data to be displayed in the multipleUserControls
. Then in the XAML file, use anItemsControl
(wrapped inside aScrollViewer
control) orListBox
and set theDataTemple
with theUserControl
.
UPDATE: Here is a working example for you as requested...
Models and ViewModels may have properties that can change. Here is a base class that works with the INotifyPropertyChanged binding interface:
public abstract class ObservableBase : INotifyPropertyChanged
{
public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
注意:此示例应用程序需要 NOT ,但此处为Binding系统的彻底性。
对于我们的示例应用,我们需要一个数据模型来绑定中
class: ObservableCollection
中的每个项目MainViewModel
NOTE: This is NOT required for this sample app but here for thoroughness for the Binding system.
For our sample app, we need a data model to bind each item in the ObservableCollection
in the MainViewModel
class:
public class PersonModel : ObservableBase
{
private string name;
public string Name
{
get { return name; }
set { Set(ref name, value); }
}
private int age;
public int Age
{
get { return age; }
set { Set(ref age, value); }
}
}
现在我们可以定义将保存我们的集合的 MainViewModel
要在 MainWindow
UI中显示的对象
Now we can define our MainViewModel
that will hold our collection of objects to be displayed in the MainWindow
UI
public class MainViewModel
{
public MainViewModel()
{
Mock();
}
public ObservableCollection<PersonModel> Persons { get; set; }
= new ObservableCollection<PersonModel>();
private Random rand = new Random();
private void Mock()
{
for (int i = 0; i < 10; i++)
{
Persons.Add(new PersonModel
{
Name = string.Format("Person {0}", i),
Age = rand.Next(20, 50)
});
}
}
}
现在我们在 UserControl中定义我们的项目模板
根据此问题的要求:
Now we define our item template in the UserControl
as required in this question asked:
<UserControl
x:Class="ItemsControlSample.PersonUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Margin="10 3"/>
<TextBlock Text="{Binding Age}" Margin="10 3" Grid.Column="1"/>
</Grid>
</UserControl>
最后,我们现在准备定义我们的 MainWindow
用户的UI视图:
Lastly, we are now ready to define our MainWindow
UI view for the user:
<Window
x:Class="ItemsControlSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ItemsControlSample"
Title="Basic ObservableCollection binding example"
WindowStartupLocation="CenterScreen" Height="400" Width="360">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.Resources>
<DataTemplate DataType="{x:Type local:PersonModel}">
<local:PersonUserControl/>
</DataTemplate>
</Grid.Resources>
<TextBlock Text="ItemsControl Example" FontWeight="Bold" Margin="4 10"/>
<Border BorderThickness="1" BorderBrush="Silver" Margin="4" Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Persons}"/>
</ScrollViewer>
</Border>
<TextBlock Text="ListBox Example" FontWeight="Bold" Margin="4 10" Grid.Column="1"/>
<ListBox ItemsSource="{Binding Persons}" Margin="4" Grid.Row="1" Grid.Column="1">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</Window>
示例应用程序显示如何显示 ObservableCollection $ c中包含的
Models
列表$ c>在绑定 ViewModel
中使用 ItemsControl
和 ListBox
使用MVVM模式和WPF绑定系统进行控制。
The sample app shows how to display a list of Models
contained in an ObservableCollection
in the bound ViewModel
using both an ItemsControl
and a ListBox
control using the MVVM Pattern and the WPF Binding system.
这篇关于如何通过MVVM中的循环创建多个usercontrol实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!