依赖属性实验案例一

目的:通过一个Student对象,实现前端两个TextBox输入值相同(此案例仅做实验,用于理解最简单的依赖属性用法,实际中不会这样用)

前端:

    <Grid>
        <StackPanel>
            <TextBox x:Name="tbx" Width="100" Height="30" Background="LightBlue"/>
            <TextBox x:Name="tbx1" Width="100" Height="30" Background="LightBlue"/>
        </StackPanel>
    </Grid>

后台:

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

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            stu.Name = tbx.Text;
            Binding bd = new Binding();
            bd.Path = new PropertyPath("Text");
            //bd.ElementName = "tbx";//注意!!!Source和ElementName不能同时使用.
            bd.Source = tbx;
            bd.Mode = BindingMode.TwoWay;
            BindingOperations.SetBinding(stu, Student.NameProperty, bd);

            Binding bd2 = new Binding();
            bd2.Path = new PropertyPath("Name");
            bd2.Source = stu;
            bd2.Mode = BindingMode.TwoWay;
            BindingOperations.SetBinding(tbx1, TextBox.TextProperty, bd2);
        }
    }

    public class Student : DependencyObject
    {
        public string Name
        {
            get
            {
                return (string)GetValue(NameProperty);
            }
            set
            {
                SetValue(NameProperty, value);
            }
        }

        public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student));
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值