WPF中的Binding:单个属性绑定与变化

绑定到非元素对象 

唯一的要求是希望显示的信息必须存储在公有属性中。WPF数据绑定基础结构不能获取私有信息或公有字段。

 

<Window x:Class="Wpf_ObservableCollection.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:Wpf_ObservableCollection"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBox x:Name="NameText" Grid.Column="0" Text="{Binding Data}"/>
        <Button Content="Chagne Data"  x:Name="ChagneData" Grid.Column="1" Click="ChagneData_Click"/>
    </Grid>
</Window>
using System.ComponentModel;
using System.Windows;

namespace Wpf_ObservableCollection
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        string data = "init";
        public string Data
        {
            get { return data; }
            set
            {
                data = value;
                //激发事件
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Data"));
                }
            }
        }

        private void ChagneData_Click(object sender, RoutedEventArgs e)
        {
            Data = "change";
        }
    }
}

注意点:

1、INotifyPropertyChanged接口;

2、修改时使用大写的Data(这是属性,公开的属性;而公开的字段不能作为绑定源),才能触发事件;

参考:

https://blog.csdn.net/hyman_c/article/details/50899904

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值