WPF中DataContext的规范写法

学习过程:初学WPF,一般会在窗口的构造函数中进行数据绑定。如下所示:

using System.Windows;

namespace WpfApp1
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel();//绑定数据
        }
    }
}```
这种写法可以实现功能,但是不推荐,因为它动了Window.xaml.cs中的代码,资深的UI设计,不会在Window.xaml.cs中增加任何代码。
我知道的方式有两种:
1、写在Window.xaml中,如下所示:
```csharp
<Window x:Class="WpfApp1.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:ViewModel/><!--绑定数据-->
    </Window.DataContext>
    <Grid>
        <Button Content="{Binding Model.SaveContent}" Command="{Binding SaveCommand}" IsEnabled="{Binding SaveIsEnabld}" Width="100" Height="25"/>
    </Grid>
</Window>

2、写在创建窗体的时候(这种方式,一般用于ViewModel构造函数需要传入值的时候):

new DataWindow() { DataContext = new DataViewModel(c,b,a) }.Show();

正常都是使用方式1,方式2仅用于少数特殊情况。例如:现在曲线的时候。先将曲线显示做成窗口,然后传值进去,最后显示出来。如果在ViewModel中传值,曲线窗口就会不那么通用。

你可能感兴趣的:(WPF,C#,wpf,ui,microsoft)