绑定代码背后

时间:2016-02-15 04:17:13

标签: c# wpf binding

我正在尝试将文本框和文本块/标签绑定到同一个类属性;文本框和文本块/标签位于不同的用户控件(父,子)中:

请参阅问题的内联评论:

    public class aa : INotifyPropertyChanged
    {
        string _s1;
        public string s1 { get return _s1; set _s1 = value; OnPropertyChanged("s1"); }

        string _s2
        public string s2 { get return _s2; set _s2 = value; OnPropertyChanged("s2"); }

        // + OnProperty changed code
    }

    public partial class usercontrola : UserControl, INotifyPropertyChanged
    {
        aa myaa;
        public usercontrola(aa myaa)
        {
            this.myaa = aa;
            this.DataContext = this;

            // binding in xaml works; I can track changes to s1 & s2 made from bound textboxes
        }

    }

    public partial class usercontrolb : UserControl, INotifyPropertyChanged
    {
        aa myaa = new aa();
        myaa.s1 = "s1";
        myaa.s2 = "s2;"

        usercontrola uca = new usercontrola(myaa);

        // this UC has a tabcontrol; we create a tab item and populate with whatever
        // usercontrol we need for the purpose.

        tabItem newTab = new tabItem();
        newTab.Contents = myaa;

        myTabControl.Items.Add(newTab);

        // in the above, binding from XAML is working



        // also this UC (not tabitem) has a named textblock (or label) which we want to bind to S1 or S2
        // depending on other logic. Therefore must be done code behind not xaml

        // This does not work:

        if (OtherLogic)
            SetBinding("s1");
        else
            SetBinding("s2");

        private SetBinding (PathName)
        {
            Binding b = new Binding();
            b.Source = myaa;
            b.Path = new PropertyPath(PathName);
            b.Mode = BindingMode.OneWay;
            b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(targetTB, TextBlock.TextProperty, b);
            // where targetTB is the target textblock/label
        }

        // Trying to get changes made in the bound textbox to update the other textblock/label. 
        // Being a textblock/label these can't be changed by user so I don't need to worry about changes in the label updating text box.

    }

1 个答案:

答案 0 :(得分:0)

问题是在设置DataContext之前设置绑定。

我有:

 ...
 if (OtherLogic)
        SetBinding("s1");
    else
        SetBinding("s2");

 ...
 this.DataContext = this;

当我将DataContext的设置移到SetBinding代码之前时,一切正常。