Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

How to databind an image source in a datatemplate in code behind

$
0
0

I'm trying to master WPF (life-long task?) and I'm creating a project that would be a Scrabble (WWF) like game so I'm displaying a 15 x 15 matrix of Squares that may or may not contain a tile.  Each tile describes a letter and contains an image of that letter. I currently have this working by having a datatemplate in an itemtemplate where I've hard-coded the xaml for the 15 columns going across the window like this:

<ListBox Name="WWFBoard" Background="Black" ><ListBox.ItemTemplate><DataTemplate ><StackPanel Name="stackSquares" Orientation="Horizontal"><TextBlock Name="Square0" Style="{StaticResource Square}" ><Image  HorizontalAlignment="Left"
                                    Width="18"
                                    Source="{Binding Path=[0].Tile.LetterImage}"></Image></TextBlock><TextBlock Name="Square1" Style="{StaticResource Square}" ><Image  HorizontalAlignment="Left"
                                    Width="18"
                                    Source="{Binding Path=[1].Tile.LetterImage}"></Image></TextBlock>

But I'm thinking that it makes more sense to do add the 15 textblocks via a loop in the code-behind, but I can't quite figure out how to set the binding for the image source.  I've seen similar questions all over but the solution always involves directly providing a URI to the image source and I cannot do that because I'm using a datatemplate (inside and item template).

Here's the code I have so far:

 WWFBoard.ItemsSource = Board.Squares;
          for (int i = 0; i < 15; i++)
			{
                Binding imageBind = new Binding(string.Format("[{0}].Tile.LetterImage",i));
                Image image = new Image();
                image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                image.Width = 18;
                //image.SetBinding(imageBind,Image.SourceProperty);

			    TextBlock tb = new TextBlock();
                tb.Name = "Square" + i.ToString();
                tb.Style = style;
 

I've also don't know if this is even possible given that I want to add each of the 15 column's textblocks to a stackpanel and I can't access it in code (I think) because it's in a template.

Thanks!


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>