WPF簡單的數據綁定

在這裏將演示一個最基礎的WPF的Binding示例:將一個類和一個控件進行綁定。this

效果預覽

輸入圖片說明

類的準備

首先建立一個名爲Student的類,這個類的實例將做爲數據源。code

class Student
{
    private string name;
    
    public string Name
    {
        get { return name;}
        set { name = value;}
    }
}

爲了讓Student的實例的值,在發生變化後能通知Binding,因此在屬性的 set語句中激發一個PropertyChanged事件,所以要實現INotifyPropertyChanged接口。xml

class Student : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string name;
        public string Name {
            get { return name; }
            set 
            {
                name = value;
                //激發事件
                if(null != PropertyChanged)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                }
        
            }
        }
    }

UI元素的準備

而後咱們咱們在窗體上準備一個TextBox和一個Button。TextBox將做爲Binding的目標,咱們會在Button的Click事件發生時改變Student對象的Name屬性值。對象

<Window x:Class="Test01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Binding" Height="110" Width="300">
    <StackPanel Background="Gray" Height="Auto">
        <TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5" Height="25" FontSize="15"/>
        <Button Content="點擊" Click="Button_Click" Margin="5" Height="25" />
    </StackPanel> 
</Window>

數據源與UI元素的鏈接

public partial class MainWindow : Window
    {
        Student stu;
        public MainWindow()
        {
            InitializeComponent();

            //準備數據源
            stu = new Student();
            
            //準備Binding
            Binding binding = new Binding();
            binding.Source = stu;
            binding.Path = new PropertyPath("Name");

            //使用Binding鏈接數據源與Bindin目標
            BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            stu.Name += "Name__";
        }
    }
相關文章
相關標籤/搜索