WPF 依赖属性使用列子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            student stu = new student();
            stu.SetBinding(student.NameProperty, new Binding("Text") { Source = textBox1 });  //text1的变化会直接显示到text3中
            textBox3.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu });
        
        }

        private void Button_Click(object sender, RoutedEventArgs e)  //不通过clr属性包装器访问
        {
            student stu = new student();
            stu.SetValue(student.NameProperty, this.textBox1.Text);
            textBox2.Text = (string)stu.GetValue(student.NameProperty);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e) //通过clr属性包装器访问
        {
            student stu = new student();
            stu.name = this.textBox1.Text;
            this.textBox2.Text = stu.name;
        }

    }

    public class student : DependencyObject
    {
        //clr属性包装器
        public string name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

        public static readonly DependencyProperty NameProperty = DependencyProperty.Register(
            "Name", typeof(string), typeof(student));
        //setbinding封装
        public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
        {
            return BindingOperations.SetBinding(this, dp, binding);
        }
    }

}

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox x:Name="textBox1" BorderBrush="Black" Margin="5"/>
        <TextBox x:Name="textBox2" BorderBrush="Black" Margin="5"/>
        <TextBox x:Name="textBox3" BorderBrush="Black" Margin="5"/>
        <Button Margin="5" Click="Button_Click" Content="不通过属性包装器访问"/>
        <Button Margin="5" Click="Button_Click_1" Content="通过属性包装器访问"/>
    </StackPanel>
</Window>

猜你喜欢

转载自blog.csdn.net/u012853614/article/details/77914294