如何将一个属性绑定到另一个类的属性(没有UI控件)



我花了几个小时在谷歌上研究我的简单任务。我正在尝试将我的变量TestString绑定到TestClass.MeinString.

如果我点击按钮"tb_tbBinding"TestString和TestClass.MyString应该保持相同的值。

相关代码:

public partial class Window_Test : Window, INotifyPropertyChanged
{
    public Window_Test()
    {
        InitializeComponent();
        DataContext = this;
        // Trying to bind TestClass.MeinString to TestString
        BindingOperations.SetBinding(TestClass, BindingTestClass.MeinStringProperty, new Binding("TestClass.MeinString") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
    }

    string _TestString = "Hello World!";
    public string TestString
    {
        get
        {
            return _TestString;
        }
        set
        {
            _TestString = value;
            OnPropertyChanged("TestString");
        }
    }
    BindingTestClass _TestClass = new BindingTestClass("Hallo Lukas!");
    public BindingTestClass TestClass
    {
        get
        {
            return _TestClass;
        }
        set
        {
            _TestClass = value;
            OnPropertyChanged("TestClass");
        }
    }
    private void btn_testclasschanger_click(object sender, RoutedEventArgs e)
    {
        TestClass.MeinString = "Changed String!";
    }
    private void btn_teststringchanger_click(object sender, RoutedEventArgs e)
    {
        TestString = "Changed Class!";
    }
}

我的自定义类:

 public class BindingTestClass : DependencyObject, INotifyPropertyChanged
    {
        public BindingTestClass(string myString)
        {
            MeinString = myString;
        }
        public string MeinString
        {
            get
            {
                return (string)GetValue(MeinStringProperty);
            }
            set
            {
                SetValue(MeinStringProperty, value);
                OnPropertyChanged("MeinString");
            }
        }
        public static readonly DependencyProperty MeinStringProperty = DependencyProperty.Register("MeinString", typeof(string), typeof(BindingTestClass), new FrameworkPropertyMetadata()
        {
            BindsTwoWayByDefault = true,
            DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
        });
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
}

谢谢你们!

尝试设置绑定的Source属性

BindingOperations.SetBinding(TestClass, BindingTestClass.MeinStringProperty, 
    new Binding("TestString") { Source=this, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });

默认情况下,绑定使用.DataContext作为绑定的源,但是在您的情况下,TestClass.DataContext没有设置为任何值。事实上,我甚至不确定这是否是DependencyObject上的有效属性。

通常,.DataContext是从WPF的可视化树中对象的父级继承的,但由于TestClass不是可视化树的一部分,因此它没有可继承的内容。

相关内容

  • 没有找到相关文章

最新更新