簡単な 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>
選択したものを次のように表示します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 がフォーカスを失い、元に戻すことができない場合、Programm はそれらを保存します。
誰かが私に例を投稿してもらえますか?
さらに、入力が無効であることがわかりません:私はそれを試しました:
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 にエラーが表示されても、私の関数はエントリが有効であることを教えてくれます。
助けてくれてありがとう!