原文 使用MVVM DataTriggers在WPF XAML视图之间切换

相关文章:

http://www.technical-recipes.com/2016/switching-between-wpf-xaml-views-using-mvvm-datatemplate/

这篇文章解决了能够根据ViewModel类的属性在不同视图之间切换的问题。

要开始使用Visual Studio,请创建一个新的WPF应用程序:

因此,当我们构建并运行应用程序时,我们有一个这样的空白窗口:

为了演示如何在不同视图之间切换WPF窗口,创建两个新的XAML视图View1.xaml和View2.xaml,每个视图由一个包含不同文本的简单TextBlock组成,以证明视图不同。

在Visual Studio项目中,右键单击项目文件夹,然后选择“添加”>“新建项”。选择用户控件(WPF)并将文件命名为View1.xaml:

在文件的xaml部分中,插入代码以在视图中显示Text,如下所示:

<UserControl
x:Class="MvvmSwitchViews.View1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:MvvmSwitchViews"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Width="800"
Height="450"
Background="Red"
mc:Ignorable="d">
<Grid>
<Button
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content=" Screen for View2"
FontSize="20">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction
PropertyName="ContentTemplate"
TargetObject="{Binding ElementName=ct}"
Value="{DynamicResource View2Template}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</UserControl>
 

重复上一步,但这次创建一个名为View2.xaml的新视图。插入View2.xaml的代码,如下所示:

<UserControl
x:Class="MvvmSwitchViews.View2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:MvvmSwitchViews"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Width="400"
Height="200"
Background="Green"
mc:Ignorable="d">
<Grid>
<Button
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content=" Screen for View1"
FontSize="20">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction
PropertyName="ContentTemplate"
TargetObject="{Binding ElementName=ct}"
Value="{DynamicResource View1Template}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</UserControl>
 

我们可能希望根据类的属性在XAML视图之间切换。例如,如果我们的ViewModel属性设置为“0”,则显示View1; 否则,如果我们的ViewModel属性设置为“1”,则显示View 2。在这种情况下,您将使用DataTrigger。

右键单击项目文件夹,创建一个非常简单的ViewModel类,选择Add> New Item。选择Class,我们将调用我们的ViewModel类MainWindowViewModel.cs:

我们的ViewModel类包含一个getter / setter属性和一个用于设置默认属性值的构造函数:

namespace MvvmSwitchViews
{
public class MainWindowViewModel
{
public int SwitchView
{
get;
set;
} public MainWindowViewModel()
{
SwitchView = ;
}
}
}
 

在我们的MainWindow.xaml中,我们使用我们创建的ViewModel类配置DataTemplate,DataContext。

还有DataTrigger,告诉应用程序显示哪个视图,如果属性设置为默认值以外的任何值:

<Window
x:Class="MvvmSwitchViews.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmSwitchViews"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
local:CenterOnSizeChangeBehaviour.CenterOnSizeChange="True"
SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="View1Template" DataType="{x:Type local:MainWindowViewModel}">
<local:View1 />
</DataTemplate>
<DataTemplate x:Key="View2Template" DataType="{x:Type local:MainWindowViewModel}">
<local:View2 />
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl x:Name="ct" Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource View1Template}" />
<Style.Triggers>
<DataTrigger Binding="{Binding SwitchView}" Value="">
<Setter Property="ContentTemplate" Value="{StaticResource View2Template}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
</Window>
 

在我们的ViewModel构造函数中,'SwitchView'属性默认为“0”,从而导致应用程序在运行时显示View1:

现在在ViewModel构造函数中将'SwitchView'属性设置为“1”:

   public MainWindowViewModel()
{
SwitchView = ;
}
 

重新构建并重新运行应用程序时,我们将显示View2屏幕,如下所示:

Window窗口自适应内容大小并居中

using System.Windows;

namespace MvvmSwitchViews
{
public static class CenterOnSizeChangeBehaviour
{
/// <summary>
/// Centers the window in the screen, when its changing its size.
/// </summary>
public static readonly DependencyProperty CenterOnSizeChangeProperty =
DependencyProperty.RegisterAttached
(
"CenterOnSizeChange",
typeof(bool),
typeof(CenterOnSizeChangeBehaviour),
new UIPropertyMetadata(false, OnCenterOnSizeChangePropertyChanged)
); public static bool GetCenterOnSizeChange(DependencyObject obj)
{
return (bool)obj.GetValue(CenterOnSizeChangeProperty);
}
public static void SetCenterOnSizeChange(DependencyObject obj, bool value)
{
obj.SetValue(CenterOnSizeChangeProperty, value);
} private static void OnCenterOnSizeChangePropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
{
System.Windows.Window window = dpo as System.Windows.Window;
if (window != null)
{
if ((bool)args.NewValue)
{
window.SizeChanged += OnWindowSizeChanged;
}
else
{
window.SizeChanged -= OnWindowSizeChanged;
}
}
}
private static void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
System.Windows.Window window = (System.Windows.Window)sender;
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = (SystemParameters.WorkArea.Width - window.ActualWidth) / + SystemParameters.WorkArea.Left;
window.Top = (SystemParameters.WorkArea.Height - window.ActualHeight) / + SystemParameters.WorkArea.Top;
}
}
}

使用MVVM DataTriggers在WPF XAML视图之间切换/Window窗口自适应内容大小并居中的更多相关文章

  1. 使用MVVM DataTemplate在WPF XAML视图之间切换

    原文 使用MVVM DataTemplate在WPF XAML视图之间切换 更新:这个技术的改进版本,一个不创建视图,可以在以下链接找到: http://www.technical-recipes.c ...

  2. WPF自定义控件与样式(13)-自定义窗体Window & 自适应内容大小消息框MessageBox

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: 自定义 ...

  3. 【转】WPF自定义控件与样式(13)-自定义窗体Window & 自适应内容大小消息框MessageBox

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等. 本文主要内容: 自定义Window窗体样式: 基于自定义窗体实现自定义MessageB ...

  4. 【逆向工具】IDA使用5-( string、图形化与视图的切换、图形化显示反汇编地址、自动注释、标签使用)

    分析petya病毒时新学会的技巧. IDA技巧1 : string 提取文件中的字符串内容,如果看到一些文件字符串可以定位到关键的函数中. view -> open subview -> ...

  5. 使用MVVM设计模式构建WPF应用程序

    使用MVVM设计模式构建WPF应用程序 本文是翻译大牛Josh Smith的文章,WPF Apps With The Model-View-ViewModel Design Pattern,译者水平有 ...

  6. 企业级架构 MVVM 模式指南 (WPF 和 Silverlight 实现) 译(2)

    本书包含的章节内容 第一章:表现模式,以一个例子呈献给读者表现模式的发展历程,我们会用包括MVC和MVP在内的各种方式实现一个收费项目的例子.沿此方向,我们会发现每一种模式的问题所在,这也是触发设计模 ...

  7. MVVM框架从WPF移植到UWP遇到的问题和解决方法

    MVVM框架从WPF移植到UWP遇到的问题和解决方法 0x00 起因 这几天开始学习UWP了,之前有WPF经验,所以总体感觉还可以,看了一些基础概念和主题,写了几个测试程序,突然想起来了前一段时间在W ...

  8. wpf多程序集之间共享资源字典--CLR名称空间未定义云云

    wpf多程序集之间共享资源字典--CLR名称空间未定义云云 分类: WPF 2012-10-28 10:57 1162人阅读 评论(0) 收藏 举报 以下介绍如何创建可用于在多个程序集之间共享的资源字 ...

  9. WPF XAML之bing使用StringFormat

    WPF XAML之bing使用StringFormat // 转化为百分比 Text="{Binding Progress, StringFormat=\{0:P\}}" < ...

随机推荐

  1. 怎样cp文件夹时忽略指定的文件夹和文件

    在备份ltedecoder程序时,须要把此文件夹拷由到bak文件夹下.但decoder文件夹下有个大文件,不须要备份,还有日志问题,也不须要备份,怎样实现呢?? 方法: cd /source-dir ...

  2. $_SERVER['DOCUMENT_ROOT']

    $_SERVER['DOCUMENT_ROOT'] 一.总结 $_SERVER 是一个包含了诸如头信息(header).路径(path).以及脚本位置(script locations)等等信息的数组 ...

  3. unity 3d开发的大型网络游戏

    unity 3d开发的大型网络游戏 一.总结 1.unity的官网上面应该有游戏列表 2.unity3D是很好的3d游戏引擎,也支持2d,也能做很多画面精良的3A级游戏 3.范围:电脑游戏,手机游戏, ...

  4. workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的)

    workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的) 一.总结 1.下面链接里面还有一个来聊的php聊天室源码可以学习 2. ...

  5. [React Native] Disable and Ignore Yellow Box Warnings in React Native

    Yellow box warnings in react native can be intrusive. We will use console.disableYellowBox to disabl ...

  6. 【SPOJ QTREE】树链剖分模板

    用线段树求解,这里注意因为求的是路径最大值,注意一下细节. #include<cstdio> #include<cstring> #include<algorithm&g ...

  7. 编程算法 - 远征队(expedition) 代码(C)

    远征队(expedition) 代码(C) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 远征队有一辆卡车须要行驶L单位的距离, 開始时, 车上有P单位的 ...

  8. QMap 的增删改查

    map 是一种数据容器,它提供一种由key 到 value 的映射.map 的key 是唯一的, 也是有序的.map 通常由近似平衡的红黑树来实现.key 的有序性,使得插入,查找节点比较有效.map ...

  9. POJ 3628 Bookshelf 2 (01背包)

    Bookshelf 2 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 7496   Accepted: 3451 Descr ...

  10. .NET Framework基础知识(四)(转载)

    .反射:是编程的读取与类型相关联的元数据的行为.通过读取元数据,可以了解它是什么类型以及类型的成员. 比如类中的属性,方法,事件等.所属命名空间System.Reflection. 例:using S ...