【发布时间】:2017-08-22 06:23:58
【问题描述】:
我正在尝试从 WPF MVVM 教程扩展应用程序作为练习。对于我在这里面临的这个特定问题,我在网上没有找到解决方案。
我有一个名为“StudentsToAdd”的带有 ObservableCollection 的 ViewModel。此集合绑定到 ItemsControl。在 ItemsControl 之外,我有一个与 ViewModel 中的“AddCommand”命令绑定的按钮。我的 XAML 的相关提取表单如下所示:
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button Content="Add" Command="{Binding AddCommand}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
<Button Content="+" Command="{Binding AddToAddListCommand}" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3,0,3,0" Margin="50,0,0,0"/>
<Button Content="-" Command="{Binding RemoveFromAddListCommand}" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="5,0,5,0" Margin="5,0,0,0"/>
</StackPanel>
<ItemsControl x:Name="AddList" ItemsSource="{Binding Path=StudentsToAdd}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Margin="0 5 3 5">
<TextBox.InputBindings>
<KeyBinding Command="{Binding ElementName=AddList, Path=DataContext.AddCommand}" Key="Return"/>
</TextBox.InputBindings>
</TextBox>
<TextBox Text="{Binding Path=LastName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Margin="0 5 3 5">
<TextBox.InputBindings>
<KeyBinding Command="{Binding ElementName=AddList, Path=DataContext.AddCommand}" Key="Return"/>
</TextBox.InputBindings>
</TextBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
+ 和 - 按钮将在 StudentsToAdd 集合中添加或删除学生。 “AddCommand”在执行时会将所有条目从 StudentsToAdd 移动到另一个名为“Students”的集合中。
现在我无法开始工作的是:每当修改 StudentsToAdd 中的学生时(在任何击键后:UpdateSourceTrigger=PropertyChanged)。我希望添加按钮在 ViewModel 中评估 AddCommand 的 CanExecute,以便相应地自动设置其 IsEnabled 属性。 ViewModel 中的命令方法目前如下所示:
private void OnAdd()
{
foreach (Student s in StudentsToAdd)
{
Students.Add(s);
}
StudentsToAdd.Clear();
StudentsToAdd.Add(new Student { FirstName = string.Empty, LastName = string.Empty });
}
private bool CanAdd()
{
if (StudentsToAdd != null && StudentsToAdd.Count > 0)
{
return StudentsToAdd.All(x => !string.IsNullOrWhiteSpace(x.FirstName) && !string.IsNullOrWhiteSpace(x.LastName));
}
return false;
}
有人知道我如何在不耦合 MVVM 部分的情况下实现这一目标吗?
【问题讨论】: