I'm having a problem trying to create a form within a Hub in a UWP app.
<Hub>
<HubSection>
<Datatemplate>
<Grid>
<TextBox x:Name="txtSerial"/>
</Grid>
</Datatemplate>
</HubSection>
</Hub>
The problem is that I can't access the control textbox
with the name to get its value. I have read in some pages that the event loaded
of the control and a field in the class could be used to make it accessible, but this would be very complicated for me since I want to create several forms with several fields each. If anyone can help me, thanks in advance.
Just as you have it at all times you can access the value of the TextBox control simply by doing this from Code behind:
However, it is a bad practice, if you are just starting it may be OK, but my recommendation is to always use MVVM and therefore never directly access the control, but let the binding take care of binding a property of a class (ViewModel) with a property of the control.
In short, I will give you all you need, or a good part of it. First thing is this helper class, it will save you loads of work later:
BindableBase
Once you have it, you must create a ViewModel, which for the example will suffice with:
Then from your code behind create an instance of this ViewModel, and initialize its values in the event
Load
like so:Now you have to modify your XAML
That's all, but there's more... a lot more... If you want, for example, that changing the value of the TextBox automatically changes the value of the variable, you can modify the code like this
Binding is not as complicated as it seems, it really makes your life a lot easier once you get used to it.
To make your life easier, I recommend you review this article:
Apps, Binding, INotifyPropertyChanged and BindableBase | XAML | C#
And I highly recommend this video course:
XAML Walkthrough
Especially the chapters dedicated to binding: 5,7,8