我已经为你构建了一个简单的测试类:
以下类(class):
public abstract class Person : INotifyPropertyChanged
public class Adult : Person
public class Child : Person
- 人:名字 + 姓氏
- 成人:公司
- child :学校
我将此数据存储在 ObservableCollection<Person>
中并想在我的窗口中显示它:
<ListView ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson}" Grid.Column="0">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock>
<Run Text="{Binding FirstName}"/>
<Run Text="{Binding LastName}"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我在 ContentPresenter
中显示的所选内容:
<ContentPresenter Content="{Binding SelectedPerson}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type local:Adult}">
<StackPanel>
<TextBlock Text="First Name:"/>
<TextBox>
<TextBox.Text>
<Binding Path="FirstName">
<Binding.ValidationRules>
<local:NotEmptyRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBlock Text="Last Name:"/>
<TextBox Text="{Binding LastName}"/> <!-- Validation same as FirstName -->
<TextBlock Text="Company:"/>
<TextBox Text="{Binding Company}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Child}">
<StackPanel>
<TextBlock Text="First Name:"/>
<TextBox Text="{Binding FirstName}"/> <!-- Validation same as above-->
<TextBlock Text="Last Name:"/>
<TextBox Text="{Binding LastName}"/> <!-- Validation same as above-->
<TextBlock Text="School:"/>
<TextBox Text="{Binding School}"/>
</StackPanel>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
现在谁能告诉我如何以正确的 MVVM 方式取消我的编辑 (CancelCommand) 或保存它们 (SaveCommand)。
现在我的程序会在 TextBox 失去焦点时保存它们并且它们无法撤消。
谁能给我发一个例子?
此外,我不知道我的输入无效: 我试过:
private void SaveCommand_Execute()
{
//this is the current window
MessageBox.Show(string.Format("Entry is {0}valid", IsValid(this) ? "" : "not "), "Validation", MessageBoxButton.OK, MessageBoxImage.Information);
}
private bool IsValid(DependencyObject obj)
{
return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
}
但即使我的 TextBox 显示错误,我的函数也会告诉我输入有效。
谢谢你帮助我!
最佳答案
如果你想要验证,你需要在你的实体上实现 INotifyDataErrorInfo
。如果要还原更改,则需要实现 IRevertibleChangeTracking
。两者都不是容易的任务,如果您以前从未做过的话。
还有另一种方法可以解决接受/取消问题。当您开始编辑 Person
时,您会将所有数据复制到 PersonViewModel
。然后,您将数据绑定(bind)到 PersonViewModel
,当用户点击保存时,将数据复制回 Person
,当用户点击取消时,忽略更改。
PersonViewModel
类不是强制性的,您可以只创建新实例 Person
,但 PersonViewModel
为您在 UI 逻辑方面提供了更大的灵 active 。例如,您可以在表示层使用密码和重复密码字段,但在业务实体中您只想使用密码。
关于c# - MVVM 获取 ContentPresenter 和 CancelEdits 的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31310131/