I made a submit button with the command that changes the text in a textblock based on whether the user entered the correct number in a textbox.
public string txtResults { get; set; }
public string txtInput { get; set; }
// Method to execute when submit command is processed
public void submit()
{
if (txtInput == number.ToString())
txtResults = "Correct!";
else
txtResults = "Wrong!";
}
'txtInput' is the member that is bound to the textbox and includes the user's input. 'txtResults' is supposed to be shown in the textblock. Right now when I click the submit button, in debugging mode, the txtResults value is assigned the "Correct!" string but it doesn't update in the view.
The XAML:
<Window x:Class="WpfMVVP.WindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfMVVP"
Title="Window View" Height="350" Width="525" Background="White">
<Grid>
<Canvas>
<Label Canvas.Left="153" Canvas.Top="89" Content="Guess a number between 1 and 5" Height="28" Name="label1" />
<TextBox Text="{Binding txtInput, UpdateSourceTrigger=PropertyChanged}" Canvas.Left="168" Canvas.Top="142" Height="23" Name="textBox1" Width="38" />
<TextBlock Text="{Binding txtResults}" Canvas.Left="257" Canvas.Top="142" Height="23" Name="textBlock1" />
<Button Command="{Binding Submit}" Canvas.Left="209" Canvas.Top="197" Content="Submit" Height="23" Name="button1" Width="75" />
</Canvas>
</Grid>
Update:
I made this change in my View Model
public class WindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private string _txtResults;
public string txtResults
{
get { return _txtResults; }
set { _txtResults = value; OnPropertyChanged("txtResults"); }
}
And now it's working! Thanks.
Please make sure your txtResults property is inheriting from INotifyPropertyChanged. Your view model should inherit from there also. Have your view model class inherit from INotifyPropertyChanged, and implement the interface. Then replace you TxtResults property with the following:
private string _txtResults = string.Empty;
public string TxtResults
{
get { return this._txtResults; }
set
{
this._txtResults= value;
this.RaisePropertyChangedEvent("TxtResults");
}
}