c# - XAML: Databinding to window not working after InitializeComponent() -


i'm new xaml , i'm trying bind score property of window (a backgammon board) control.

i able work follows via code behind:

public partial class bgboard : window {     public bgboard()     {         initializecomponent();         datacontext = this;         _score = 999;     }     private int _score;     public string score { { 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, wanted declare datacontext in xaml instead of code behind. removed 'datacontext = this' code behind , added following property window in xaml :

datacontext="{binding relativesource={relativesource self}}" 

now score no longer displayed on user interface.

however, if initialize score in code behind before call initilalizecomponent(), score displayed again:

public bgboard() {     _score = 999;     initializecomponent();  }    

so question is, should in xaml make sure score displayed correctly each time modified in code behind (and not when initialized before initializecomponent()?

you can data bind dependencyproperty of dependencyobject. window dependencyobject, need dependencyproperty... there's no need convert value string first. try this:

public static dependencyproperty scoreproperty =      dependencyproperty.register("score", typeof(int), typeof(bgboard));  public int score {     { return (int)getvalue(scoreproperty); }     set { setvalue(scoreproperty, value); } }  public bgboard() {     score = 999;     initializecomponent();  }  

if use dependencyproperty, can data bind xaml file without setting window.datacontext @ all:

<textblock x:name="player_score" text="{binding score, relativesource={relativesource      ancestortype={x:type yourlocalxamlnamespaceprefix:bgboard}}}"/> 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -