0

I have a WPF application that has a text box with binding like so:

   <TextBox Grid.Row="2" x:Name="MyTextBox">
        <TextBox.Text>
        <Binding  Path="Name"
                     UpdateSourceTrigger="PropertyChanged"/>
        </TextBox.Text>
    </TextBox>

Now, I wnt to programatically set the text. Here's the code behind:

  public string Name { get; set; }
  public MyUserControl() //the constructor
    {
        InitializeComponent();
        Name = "some text";
    }

When I do this, the text box is empty when i run the app. If i remove the binding:

    <TextBox Grid.Row="2" x:Name="MyTextBox">
    </TextBox>

I can set the text in code behind and it appears when I run the app.

     MyTextBox.Text = "some text";

How do i set the text of a text box in code behind when the binding property is set? Thanks

Clemens
  • 123,504
  • 12
  • 155
  • 268
BoundForGlory
  • 4,114
  • 15
  • 54
  • 81
  • Kindly show your viewmodel implementation have implemented it? – Smits Apr 02 '20 at 03:56
  • If you just copy the code i posted and try to set the text, you'll see it doesnt work. I do not have any viewmodel implementation. I will, but i have to get passed this first – BoundForGlory Apr 02 '20 at 04:09
  • If you have to use the bindings, then you have to set the data context and need to create the "Name" property and just write your binding code inside tag. – Smits Apr 02 '20 at 04:21
  • i've updated my question. I tried you're solution and i still dont see the text – BoundForGlory Apr 02 '20 at 04:34
  • Given the little bit of code you posted, it seems your text box is inside the user control. The most obvious problem is that you haven't set the source of the binding. It should be (probably) `RelativeSource={RelativeSource AncestorType=UserControl}`. See marked duplicate. Note also in the marked duplicate that the source property is a dependency property. You should do this as well, so that the client of the user control, rather than the user control itself, can provide a view model and its property as the source for the user control's `Name` property, rather than the user control setting it. – Peter Duniho Apr 02 '20 at 05:10
  • I think im on the right path. I asked a new question https://stackoverflow.com/questions/60985151/validation-rules-syntax-for-textbox-wpf – BoundForGlory Apr 02 '20 at 06:08

0 Answers0