0

Sorry for this basic question

I have a data model :

class data_test
    {
        public string textdata { get; set; }
        public bool booldata { get; set; }
        public bool checkdata { get; set; }
        public data_opt enumdata { get; set; }
    }

Here's Enum :

   enum data_opt
        {
            managed = 1,
            unmanaged = 2 ,
            mixed = 3
        }

Then I create a data model :

    var n_Data = new data_test()
    { textdata = "test data",
    booldata = false,
    checkdata = true ,
    enumdata = data_opt.mixed
    };

And I create a text box from code behind :

 var text_box = new TextBox();

Now I want to bind text_box.Text property to n_Data.textdata from code behind

The same way DataGrid works , two-way connection with real-time update.

I found some pages :

Binding String Property in Code-Behind TextBlock

WPF Data Binding to a string property

Binding string property to object

Unfortunately , none of them worked for me , Here's my code to bind:

Binding binding = new Binding();
binding.Path = new PropertyPath("textdata");
binding.Source = n_Data;
text_box.SetBinding(TextBlock.TextProperty, binding);

Also I tried this :

    Binding binding = new Binding();
    binding.Path = new PropertyPath("textdata");
    binding.Source = n_Data;
    BindingOperations.SetBinding(text_box, TextBlock.TextProperty, binding);

Both of them don't work , What am I doing wrong ?

8
  • You have not set datacontext to your viewmodel. You also haven't implemented inotifyprooertychanged, which you should do EVEN if you don't want to change data in the vm and see the view respond. Commented Mar 16, 2019 at 18:01
  • It's not necessary to set the DataContext when you explicitly set the Binding's Source. And of course you only have to implement INotifyPropertyChanged when your logic actually requires a property change notification. Commented Mar 16, 2019 at 18:03
  • @Andy As I know there's no need to INotifyPropertyChanged and DataContext for single binding ... I did what Fruchtzwerg said and it's working fine now... Commented Mar 16, 2019 at 20:10
  • @Clemens , It's working fine , Do I really need INotifyPropertyChanged ??? I change value and GUI change and I change GUI and value change , Why I need INotifyPropertyChanged ? Commented Mar 16, 2019 at 20:11
  • As said, you do of course not need to implement when it is not required. Commented Mar 16, 2019 at 20:16

1 Answer 1

0

Since your target is a TextBox, you can't use TextBlock.TextProperty as property to bind. You need to use TextBox.TextProperty:

text_box.SetBinding(TextBox.TextProperty, binding);
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.