WPF xaml MVVM动态绑定实现

UI与后端绑定有两种方式

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

 public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }        

 

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

window中如下:

<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中如下

    <Page.DataContext>
        <viewmodel:LoginViewModel />
    </Page.DataContext>

 

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

posted @ 2023-03-04 18:13  盛沧海  阅读(354)  评论(0编辑  收藏  举报