WPF例3-单击按钮更改数据前端实时刷新

2020-01-27  本文已影响0人  quchangTJU

一、在MainWindow类中,输入propdp然后双击TAB键,注册一个string类型的依赖属性,名为Test。
二、绑定简单的数据,Label控件可以直接设置DataContext属性。我们也可以设置MainWindow的DataContext属性,因为所有控件都在MainWindow下,Label控件会自动向上寻找可用的DataContext,这里直接设置MainWindow的DataContext属性,免去了设置Label的DataContext属性的步骤。
三、设置路由事件,可以让MainWindow监听窗口内的按钮单击事件来响应处理函数Window_Click,无需让按钮控件单独设置响应函数。

MainWindow.xaml.cs文件代码

using System.Windows;

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;  //设置窗口的数据上下文为当前对象,Label控件会找到当前MainWindow对象的Test属性
        }

        //注册依赖属性Test
        public string Test
        {
            get { return (string)GetValue(TestProperty); }
            set { SetValue(TestProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TestProperty =
            DependencyProperty.Register("Test", typeof(string), typeof(MainWindow));
        //按钮响应函数
        private void Window_Click(object sender, RoutedEventArgs e)
        {
            Test += "1";
        }
    }
}

MainWindow.xaml文件代码

<Window x:Class="WpfApp3.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:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" ButtonBase.Click="Window_Click">
    <Grid>
        <Label Content="{Binding Test}" HorizontalAlignment="Left" Margin="263,150,0,0" VerticalAlignment="Top" Width="214"/>
        <Button Content="添加字符串" HorizontalAlignment="Left" Margin="263,247,0,0" VerticalAlignment="Top" Width="214"/>
    </Grid>
</Window>
代码效果
上一篇 下一篇

猜你喜欢

热点阅读