WPF 数据绑定到类

Aug 17, 2016 19:12 · 189 words · 1 minute read

首先, 类的声明需要做一些手脚

using System.ComponetModel;

public class Status : INotifyPropertyChanged
    {
        private string _status;

        public string status
        {
            get { return _status;}

            set {
                _status = value;
                OnPropertyChanged("status");
            }

        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

基本上是固定的设置 只要在 setter 部分执行OnPropertyChanged(属性名) 即可正确地讲当次改动通知到对应的binding, 准确的说是通知到DataContext

窗口处理 (*.xaml.cs)

private Status status = new Status();

设置组件的数据

this.DataContext = status;

或者

label.DataContext = status;

都可以

界面(*.xaml)

<Label x:Name="label" Content="{Binding Path=status}" HorizontalAlignment="Left" FontSize="50"  Height="75" Margin="90,93,0,0" VerticalAlignment="Top" Width="317"/>