繁体   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