问题:我应该如何将新的 child 添加到我的用户控件中?我被告知 View 模型不应该知道任何关于 View 的信息,而是使用绑定(bind)。现在我创建了一个项目控件,并将我的绑定(bind)路径设置为包含标签数组的属性 MyLabels。它不起作用,老实说,我不确定推荐的方法是什么让它起作用。
我的 XAML 的项目控件(位于我的用户控件内的某处):
<UserControl x:Class="Test.Main"
x:Name="this"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="1000">
<ScrollViewer Height="400" Width="900">
<StackPanel Width="900">
<Grid x:Name="myGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ItemsControl ItemsSource="{Binding Path=MyLabels}"/>
</Grid>
<Image PreviewMouseDown="AddLabel""/>
</StackPanel>
</ScrollViewer>
</StackPanel>
</UserControl>
这是我的 View 模型:
namespace Test {
public partial class Main {
public ObservableCollection<string> MyLabels { get; set; } = new ObservableCollection<string>();
public Main() {
InitializeComponent();
DataContext = this;
}
public void AddLabel(object sender, RoutedEventArgs e) {
for (int i = 0; i < 2; i++) {
MyLabels.Add("eee");
}
}
}
}
最佳答案
将 View 的 DataContext
设置为 View 模型的实例:
public Main() {
InitializeComponent();
DataContext = this;
}
然而, View 模型应该是它自己的一个类:
public MainWindow() {
InitializeComponent();
DataContext = new ViewModel();
}
它不应该创建任何 Label
元素,而是 strings
:
public class ViewModel
{
public List<string> MyLabels { get; set; } new List<string>();
public ViewModel()
{
AddLabels();
}
public void AddLabels()
{
for (int i = 0; i < 5; i++)
{
MyLabels.Add("Sample");
}
}
}
Label
是一种用户界面元素类型,它们仅属于 View 。
另请注意,您只能绑定(bind)到公共(public)属性。
It works now, only problem is im not sure how to add actual labels without violating the MVVM pattern.
您在 ItemsControl
的 ItemTemplate
中添加 Label
元素。此模板定义源集合中项目的外观,即本例中的 string
:
<ItemsControl ItemsSource="{Binding Path=MyLabels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
关于c# - 使用 ViewModel 将子项添加到用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803442/