WPF ; ; WPF : (, , , - )
ViewModel.cs:
public class ViewModel : INotifyPropertyChanged
{
private bool _isTwo;
public bool IsTwo
{
get { return _isTwo; }
set
{
_isTwo = value;
OnPropertyChanged("IsTwo");
}
}
public ICommand Switch
{
get { return new RelayCommand((_) => { IsTwo = !IsTwo; }, (_) => true); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class RelayCommand : ICommand
{
private readonly Action<object> _action;
private readonly Func<object, bool> _predicate;
public RelayCommand(Action<object> action, Func<object, bool> predicate)
{
_action = action;
_predicate = predicate;
}
public bool CanExecute(object parameter)
{
return _predicate(parameter);
}
public void Execute(object parameter)
{
_action(parameter);
}
public event EventHandler CanExecuteChanged;
}
MainWindow
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<DockPanel>
<Button DockPanel.Dock="Top" Command="{Binding Switch}"> Switch </Button>
<UserControl>
<ContentControl >
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Content">
<Setter.Value>
<local:UserControl1 DataContext="{Binding UserControl1ViewModel}"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsTwo}" Value="True">
<Setter Property="Content">
<Setter.Value>
<local:UserControl2/>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</UserControl>
</DockPanel>
() UserControls :


. , , , . DockPanel. , , .
[]
, , , , ctor
public UserControl1()
{
InitializeComponent();
MessageBox.Show("Created UserControl1");
}
public UserControl2()
{
InitializeComponent();
MessageBox.Show("Created UserControl2");
}
. UserControl2 , . , ; , WPF.