I have a basic project in WPF.
All it does it retrieve / update products.
As shown in the image below, the user enters an ID, the data is then displayed according to it, and the user is able to change the data and click 'Save Product' to save it to the database.
The GetProduct(int id)
function retrieves a product by the ID provided.
The SaveProduct()
function saves the changed fields.
Also, there are two DataTemplates:
1) For the ProductModel - includes 3 textboxes: ProductId, ProductName, UnitPrice.
2) For the ProductViewModel - includes the save/get buttons + a textbox for the user to enter the id of the desired product.
What I'm trying to do is get the changed data when a user clicks the 'Save Product' button.
The most ideal way in my opinion, is to use Binding
.
Each textbox is already binded, but I have no idea how to get the binded data.
Here is an example of a binded textbox in the FIRST DataType (ProductModel):<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ProductId}" Margin="5" Width="150" />
There is one for each of the following properties: ProductId
, ProductName
and UnitPrice
.
IMPORTANT!: The Get/SaveProduct()
functions are in the ProductViewModel class
, while the actual product class is - you guessed it - ProductModel
. The ProductViewModel
class holds a variable that contains the current product displayed.
This is the button that's used to save the info - it is written in the SECOND DataType (ProductViewModel):<Button Content="Save Product" DockPanel.Dock="Right" Margin="10,2" VerticalAlignment="Center" Command="{Binding Path=SaveProductCommand}" Width="100" />
The SaveProductCommand
command simply fires the SaveProduct()
function.
I have a few questions regarding this whole subject:
What does it mean when a binding is used like this :
{Binding ProductId}
?The default binding mode for textboxes is TwoWay as far as I remember. But in this case, ProductId/Name + UnitPrice are not dependency properties, therefore is it right that the binded values do not update/sent back when the text in the textboxes is changed? (Since there isn't an event attached to it...)
A data context was never configured in my project, but all of the "binding tags" in my XAML pages don't seem to have a defined source. Could it be that the source is actually the
DataType
in theDataTemplate
that includes the binded objects?The SECOND DataTemplate (the ProductViewModel one) has this ContentControl tag:
<ContentControl Margin="10" Content="{Binding Path=CurrentProduct}" />
.
What is it's purpose?If a TwoWay binding were/does occur, how do I get the values from within the
SaveProduct()
function? Do I just refer to, sayCurrentProduct.ProductName
to get the changed name?
Much thanks to everyone who takes their time to answer - I appreciate it so much!