Reputation: 8531
Title pretty much says it all. The score is being displayed as 0 (which is what I initialized it to). However, when updating the Score it's not propagating to the UI textBlock. Thought this would be pretty simple, but I'm always running into problems making the switch from Android :) Am I suppose to be running something on the UI thread??
I'm trying to bind to the "Score" property.
<TextBox x:Name="text_Score" Text="{Binding Score, Mode=OneWay}" HorizontalAlignment="Left" Margin="91,333,0,0" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Height="148" Width="155" FontSize="72"/>
Here is my holder class
public class GameInfo
{
public int Score { get; set; }
public int counter = 0;
}
**Note: Make sure you don't forget to add {get; set;} or else nothing will show up.
and this is where I'm trying to set it
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
info.counter = (int)e.Parameter;
text_Score.DataContext = info;
}
P.S. To reiterate, I'm going for OneWay. I only want to display the score and have it undated when the variable changes. I plan on disabling user input.
Here is the full working code example. The only thing that had to change was my holder class. Thanks Walt.
public class GameInfo : INotifyPropertyChanged
{
private int score;
public int Score {
get { return score; }
set
{
if (Score == value) return;
score = value;
NotifyPropertyChanged("Score");
}
}
public int counter = 0;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Upvotes: 1
Views: 2624
Reputation: 7037
In XAML binding your underlying class needs to inform the binding framework that the value has changed. I your example, you are setting the counter in the OnNavigatedTo event handler. But if you look at your GameInfo class, it's a simple data object.
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. So in your case, change the class as follows
public class GameInfo : INotifyPropertyChanged
{
private int _score;
public int Score
{
get
{
return this._score;
}
set
{
if (value != this._score)
{
this._score = value;
NotifyPropertyChanged("Score");
}
}
}
public int counter = 0; // if you use _score, then you don't need this variable.
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
See the MSDN article for more information INotifyPropertyChanged
Upvotes: 2