WPF中DataContext的规范写法

12 篇文章 2 订阅

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

using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    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中传值,曲线窗口就会不那么通用。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C#气氛组队员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值