nikhil
nikhil

Reputation: 9385

DataBinding TextBox with an Integer value WP7

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?

Upvotes: 0

Views: 2289

Answers (2)

ChrisF
ChrisF

Reputation: 137148

You don't need to bind to a string. You can bind directly to an integer:

private int _userScore;
public int UserScore
{
    {
        return _userScore;
    }
    set
    {
        _userScore = value;
        NotifyPropertyChanged("UserScore");
    }
}

And you'd simply set it like this:

public Game()
{
    UserScore = 0;
}

Then change your TextBlock to:

<TextBlock Margin="28,74,242,386" Name="scoreTextBlock" Text="{Binding UserScore}" />

You've set the DataContext on the view, you don't need to do it again. If you want to display the word "Score" you'll have to use a second TextBlock.

This should work.

Upvotes: 4

Ritch Melton
Ritch Melton

Reputation: 11598

I think you are attempting to bind on this line:

<TextBlock Margin="28,74,242,386" Name="scoreTextBlock" Text="SCORE" DataContext="{Binding UserScore}"/>

but that is is incorrect. The DataContext property should be the instance of the game class, and Text property should be the score. Something like this:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="SCORE:"/>
    <TextBlock Text="{Binding UserScore}"/>
</StackPanel>

That code still needs a datacontext, but I'm not sure how you are instantiating and locating the instance, so I declined to add any example code for it. Keep @ChrisF's comments in mind also.

Upvotes: 2

Related Questions