wpf data binding

 

    public partial class Window2 : Window
    {   
        public Person vmPerosn = new Person();
        public Window2()
        {
            InitializeComponent();

            vmPerosn.Name = "Jack Zhao";
            vmPerosn.Phone = "13666666666";
            vmPerosn.idNo = "110110110110110110";
            //tb1.DataContext = vmPerosn;
            this.DataContext = vmPerosn;
            //< TextBox Name = "tb1" Grid.Column = "3"  Text = "{Binding Path=Name}"  TextWrapping = "Wrap" VerticalContentAlignment = "Center" HorizontalContentAlignment = "Stretch" />

            Binding myBinding = new Binding();
            myBinding.Source = vmPerosn;
            myBinding.Path = new PropertyPath("Phone");
            myBinding.Mode = BindingMode.TwoWay;
            myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(tb2, TextBox.TextProperty, myBinding);
        }
    }

  

 two way binding

public partial class Window2 : Window
{   
    public Person vmPerosn = new Person();
    public Window2()
    {
        InitializeComponent();

        vmPerosn.Name = "Jack Zhao";
        vmPerosn.Phone = "13666666666";
        vmPerosn.idNo = "110110110110110110";
        //tb1.DataContext = vmPerosn;
        this.DataContext = vmPerosn;
        //< TextBox Name = "tb1" Grid.Column = "3"  Text = "{Binding Path=Name}"  TextWrapping = "Wrap" VerticalContentAlignment = "Center" HorizontalContentAlignment = "Stretch" />
        // < TextBox Name = "tb1" Grid.Column = "3"  Text = "{Binding Path=Name, Mode = TwoWay,  UpdateSourceTrigger=PropertyChanged}"  TextWrapping = "Wrap" VerticalContentAlignment = "Center" HorizontalContentAlignment = "Stretch" TextChanged = "tb1_TextChanged" />

        Binding myBinding = new Binding();
        myBinding.Source = vmPerosn;
        myBinding.Path = new PropertyPath("Phone");
        myBinding.Mode = BindingMode.TwoWay;
        myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(tb2, TextBox.TextProperty, myBinding);
    }

    private void tb1_TextChanged(object sender, TextChangedEventArgs e)
    {
        MessageBox.Show(vmPerosn.Name);
    }

    private void tb2_TextChanged(object sender, TextChangedEventArgs e)
    {
        MessageBox.Show(vmPerosn.Phone);
    }
}

 

posted @ 2023-12-09 23:49  zyip  阅读(9)  评论(0编辑  收藏  举报