我为您构建了一个简单的 TestClass:
以下课程:
public abstract class Person : INotifyPropertyChanged
public class Adult : Person
public class Child : Person
- 人:名字+姓氏
- 成人:公司
- 孩子:学校
我将此数据存储在一个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>
我在 a 中显示的选定一个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>
现在谁能告诉我如何取消我的编辑(CancelCommand)或以正确的 MVVM 方式保存它们(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 显示错误,我的函数也会告诉我该条目是有效的。
感谢你们对我的帮助!