I want to bind the user score to a text box on the windows phone app in silverlight. here is the skeleton of my Game Class
public class Game : INotifyPropertyChanged
{
private int _userScore;
public string UserScore {
{
return _userScore.ToString();
}
set
{
_userScore = Convert.ToInt32(value);
NotifyPropertyChanged("UserScore");
}
}
public Game()
{
UserScore = "0";
}
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
In my XAML I have
<TextBlock Margin="28,74,242,386" Name="scoreTextBlock"
Text="SCORE" DataContext="{Binding UserScore}" />
and in the MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
Game theGame = new Game();
DataContext = theGame;
}
The Question
When I run the App, the score gets modified correctly but it doesn’t display inside the scoreTextBlock.
Is there something that I’m doing wrong?
You don’t need to bind to a
string. You can bind directly to an integer:And you’d simply set it like this:
Then change your
TextBlockto:You’ve set the
DataContexton the view, you don’t need to do it again. If you want to display the word “Score” you’ll have to use a secondTextBlock.This should work.