依赖属性实验案例一

目的:通过一个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));
    }

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...