[SOLVED] WPF TextBox.Text returns default value

Issue

This Content is from Stack Overflow. Question asked by Bohdan Petrenko

I’m making a small application using .NET Core 6 WPF. I’m trying to get user input from a TextBox, but it returns a value I set through XAML.
This is how I declare a TextBox:

<TextBox Name="TaskTextBox" Margin="0, 0, 0, 20" Text="Task" Style="{StaticResource InputFieldStyle}"/>

And here is how I try to get the input:

var taskText = TaskTextBox.Text; // the value of Text property is "Task", but I entered "Test"

I request TaskTextBox.Text when the button is pressed.

I don’t know how to fix this.



Solution

When dealing with dates, use date properties on whatever your binding source. Same with other data types like int, decimal, float, etc. If you set the textbox control to a binding of a specific type, or a date picker control to a date field respectively, YOU dont have to worry as much about a valid value or type conversion.

So, on your underlying binding source DATACONTEXT, have a property like

public DateTime myDate { get; set;}

Then, in have a DatePicker control and bind the SelectedDate to the date property exposed. Then you get built-in calendar style features, can do black-out dates, and more.

FEEDBACK.

By looking at your sample XAML portion, it LOOKS like you are not doing MVVM pattern (better to learn/extend to that). It looks like your code is all lying within your YourClass.xaml (Visual component) and YourClass.xaml.cs (Code behind for action). I see this from your button binding of SaveButton_OnClick which recognizes the .xaml.cs for the source. This is basically the binding "Context" of the control that you are putting all your stuff into (textbox, button, labels, etc.).

So, all that being said, just add a public property as described in the same .xaml.cs that your SaveButton_OnClick is located. Just for grins, you have a textbox used for a date, but try doing a datepicker control. For grins, just to follow, add another textbox just for simple purposes of following the binding. Notice that on each, I put a default value, so when you run the form, you SHOULD see these values immediately just to KNOW the bindings are accurate.

public DateTime myDate { get; set;} = DateTime.Now.Date;

public int myIntProp { get; set;} = 32;

Now, in your .xaml file put something like

<DatePicker SelectedDate="{Binding myDate,
    UpdateSourceTrigger=PropertyChanged}" />

<TextBox Text="{Binding myIntProp}" />

Now, when you click on the button and check the values (after you have changed them to something other than their default upon creation), you SHOULD see the new values and in their proper data type respectively.


This Question was asked in StackOverflow by Bohdan Petrenko and Answered by DRapp It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?