WPF xaml MVVM动态绑定实现

UI与后端绑定有两种方式

1.在xaml的后台代码中进行设置,如下    

1
2
3
4
5
public MainWindow()
       {
           InitializeComponent();
           this.DataContext = new MainWindowViewModel();
       }        

 

2.在xaml代码中进行相应的配置,只是配置时针对window与page有些差别。

window中如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<Window x:Class="WpfMvvm.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:viewmodels="clr-namespace:WpfMvvm.ViewModels"  d:DataContext="{d:DesignInstance Type=viewmodels:MainWindowViewModel}"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <viewmodels:MainWindowViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBox Name="tb1" Grid.Row="0" Background="AliceBlue" FontSize="24" Margin="4" Text="{Binding Input1}"/>
        <TextBox Name="tb2" Grid.Row="1" Background="AliceBlue" FontSize="24" Margin="4" Text="{Binding Input2}"/>
        <TextBox Name="tb3" Grid.Row="2" Background="AliceBlue" FontSize="24" Margin="4" Text="{Binding Result}"/>
        <Button Name="addButton" Grid.Row="3" Content="Add" Width="120" Height="80" Command="{Binding AddCommand}"/>
        <Button Grid.Row="4" Content="test" Command="{Binding AddCommand}"/>
    </Grid>
</Window>

 

page中如下

1
2
3
<Page.DataContext>
    <viewmodel:LoginViewModel />
</Page.DataContext>

 

参考链接:WPF进阶之MVVM教程(一) - 知乎 (zhihu.com)

posted @   盛沧海  阅读(370)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2022-03-04 sql server profiler使用教程
点击右上角即可分享
微信分享提示