1

I'm trying to create a label at runtime and connect it's Content property to another TextBox control which is in my UserControl called MyLabelSettings.

This is what I got so far:

Label currCtrl = new Label();
MyLabelSettings currCtrlProperties = new MyLabelSettings();

// Bindings to properties
Binding binding = new Binding();
binding.Source = currCtrlProperties.textBox_Text.Text;
binding.Path = new PropertyPath(Label.VisibilityProperty);
BindingOperations.SetBinding(currCtrl.Content, Label.ContentProperty, binding);

The last row shows an error which I did not figure out how to solve:

The best overloaded method match for 'System.Windows.Data.BindingOperations. SetBinding(System.Windows.DependencyObject, System.Windows.DependencyProperty, System.Windows.Data.BindingBase)' has some invalid arguments

I have in MyLabelSettings the implementation of INotifyPropertyChanged which has the following code when the TexBox.Text changes

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    InvokePropertyChanged(new PropertyChangedEventArgs("TextChanged"));
}

Is there a better way to bind these 2? Or am I doing something wrong in this one?

Thanks!

1 Answer 1

1

The problem is simpler than you realize:

This:

binding.Source = currCtrlProperties.textBox_Text.Text;
binding.Path = new PropertyPath(Label.VisibilityProperty);
BindingOperations.SetBinding(currCtrl.Content, Label.ContentProperty, binding);

Should be this:

//The source must be an object, NOT a property
binding.Source = currCtrlProperties;
//Since the binding source is not a DependencyObject, we using string to find it's property
binding.Path = new PropertyPath("TextToBind");
BindingOperations.SetBinding(currCtrl, Label.ContentProperty, binding);

Before, you were attempting to bind the value to an object's property via a property. Now, you're binding the value to an object's property via an object (:

Notes:

  • You are attempting to bind the text of a control that exists in an instance of a class you just made.

    MyLabelSettings currCtrlProperties = new MyLabelSettings();
    

    I base this assumption off this line:

    currCtrlProperties.textBox_Text.Text;
    

    Which appears to contain a text control of some sort. Rather, you want bind the text of a property that exists in an instance of a class you make, not a control.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.