user3277372
user3277372

Reputation: 5

XAML: Databinding to window not working after InitializeComponent()

I'm new to XAML and i'm trying to bind the score property of my window (a backgammon board) to a control.

I was able to get it to work as follows via code behind:

public partial class BgBoard : Window
{
    public BgBoard()
    {
        InitializeComponent();
        DataContext = this;
        _Score = 999;
    }
    private int _Score;
    public string Score { get { return _Score.ToString(); } }
}

XAML

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    xmlns:bgb="clr-namespace:BackgammonBoard"
    xmlns:Properties="clr-namespace:BackgammonBoard.Properties"      x:Class="BackgammonBoard.BgBoard"
    Title="Backgammon board" Width="750" Height="500" MinWidth="375" MinHeight="250">    
    <TextBlock x:Name="Player_Score" Text="{Binding Score}"/>
</Window>

Next, I wanted to declare the datacontext in XAML instead of code behind. I removed 'Datacontext = This' from code behind and added the following property to my window in XAML :

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Now the score is no longer displayed on my user interface.

However, if I initialize the score in code behind before the call to InitilalizeComponent(), the score is displayed again:

public BgBoard()
{
    _Score = 999;
    InitializeComponent(); 
}   

So my question is, what should i do in XAML to make sure the score is displayed correctly each time it is modified in code behind (and not only when it is initialized before InitializeComponent()?

Upvotes: 0

Views: 500

Answers (2)

Sheridan
Sheridan

Reputation: 69987

You can data bind to a DependencyProperty of a DependencyObject. The Window is a DependencyObject, so all you need is a DependencyProperty... there's also no need to convert your value into a string first. Try this:

public static DependencyProperty ScoreProperty = 
    DependencyProperty.Register("Score", typeof(int), typeof(BgBoard));

public int Score
{
    get { return (int)GetValue(ScoreProperty); }
    set { SetValue(ScoreProperty, value); }
}

public BgBoard()
{
    Score = 999;
    InitializeComponent(); 
} 

If you use a DependencyProperty, then you can even data bind to it from the XAML file without setting the Window.DataContext at all:

<TextBlock x:Name="Player_Score" Text="{Binding Score, RelativeSource={RelativeSource 
    AncestorType={x:Type YourLocalXamlNamespacePrefix:BgBoard}}}"/>

Upvotes: 0

Clueless
Clueless

Reputation: 1200

the reason you don't see the score is that the property doesn't raise a "change notification" to the UI, you need to implement "INotifyPropertyChanged" (click the link for explanation)

Upvotes: 1

Related Questions