簡體   English   中英

從代碼后面進行綁定

[英]Binding from code behind

我正在嘗試將文本框和文本塊/標簽綁定到相同的class屬性; 文本框和文本塊/標簽位於不同的用戶控件(父,子)中:

請查看在線注釋中的問題:

    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.

    }

問題出在設置DataContext之前是設置綁定。

我有:

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

 ...
 this.DataContext = this;

當我將DataContext的設置移到SetBinding代碼之前時,所有方法都可以使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM