Reputation: 144
I'm attempting to build a golf game tracking program that uses a canvas to hold an arranged set of buttons and databound items for each player. Because the number of people in a game is dynamic, I need to be able to build the canvases on the fly and bind them on the fly as well. the problem I'm having is setting up the databinding. If I attempt to bind in code then the text for the binding (text={Binding}) always comes out as though it were a string literal instead of an actual binding. To get around this I attempted to build a template of the canvas, but I can't find a way to actually apply the template to a new canvas as I build out new players.
So with all that in mind, what is the best way to either A) build a template canvas with all my controls so I can just copy and bind to each player, or B) build the text bindings dynamically without having to resort to XAML?
Edit: The following was added for clarification on how I'm creating a textblock.
TextBlock newBlock = new TextBlock
{
Text = "{Binding}",
FontSize = 42,
DataContext = Player.SomeStat,
Name = Player.PlayerName ,
};
The value shown on the screen for the textblock (instead of what it should be) is: {Binding}
Upvotes: 0
Views: 244
Reputation: 2535
Assuming you want to bind to the datacontext of the Control instance your code lives in...
textBlock.SetBinding(TextBlock.TextProperty, new Binding("Foo"));
textBlock.DataContext = this.DataContext;
Upvotes: 0
Reputation: 1402
To create a Binding in code you need to go some extra steps:
object myDataObject = DataContext;
Binding myBinding = new Binding();
myBinding.Source = myDataObject;
myBinding.Path="."; // not sure if required
newBlock.SetBinding(TextBlock.TextProperty, myBinding);
Upvotes: 1