在视图之间切换时,可以使用DataTemplate和Triggers来实现。以下是一个简单的示例,展示了如何使用DataTemplate和Triggers在视图之间切换:
<DataTemplate x:Key="View1Template">
<Grid>
<TextBlock Text="View 1" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="View2Template">
<Grid>
<TextBlock Text="View 2" />
</Grid>
</DataTemplate>
</Window.Resources>
public class ViewModel : INotifyPropertyChanged
{
private string _currentView;
public string CurrentView
{
get { return _currentView; }
set
{
_currentView = value;
OnPropertyChanged("CurrentView");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentView}" Value="View1">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl><ContentControl ContentTemplate="{StaticResource View2Template}" Visibility="Collapsed">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentView}" Value="View2">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
((ViewModel)DataContext).CurrentView = "View1";
这样,就可以根据视图模型中的属性值在视图之间切换了。
领取专属 10元无门槛券
手把手带您无忧上云