【发布时间】:2017-06-28 13:09:18
【问题描述】:
问题:如何将新子项添加到我的用户控件?我被告知 viewmodel 不应该对视图有任何了解,而是使用绑定。现在我创建了一个项目控件并将我的绑定路径设置为包含标签数组的属性 MyLabels。它不起作用,老实说,我不确定推荐的方法是什么。
我的 XAML 的 itemscontrol(在我的用户控件中的某处):
<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>
这是我的视图模型:
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");
}
}
}
}
【问题讨论】:
-
您是否检查了是否在标签中添加了一些文本?
-
是的,我做到了。它没有工作
-
还有为什么需要从
UserControl继承Main?我认为您可以删除该继承、事件(因为没有人会提出您的事件),而是将 VM 保留为纯 POCO。 -
@SivaGopal 谢谢,改了。
-
@jαsοndιnAlt 我可以设置一个 x:Name 并直接添加孩子,但这不是一个好习惯。这个 vm 的作用是将数据绑定到用户控件,并在用户单击按钮时添加新元素。