I have tried several different ways to get a simple DataTemplate example to work. But, I am not having any luck. The data context for the XAML below is being set in the code-behind. The two code examples included here are wrapped in the element in my application but, that is the only outside consideration. The first code example works. It displays the data. But, if I put the functionality in a DataTemplate, and then try to use the template, it does not work.
Working Example:
<Canvas Height="100" Width="300">
<TextBlock Text="{Binding Path=DataSheet.Item.ClassId}" Canvas.Left="10"></TextBlock>
<TextBlock Text="{Binding Path=DataSheet.Item.ClassName}" Canvas.Right="100"></TextBlock>
</Canvas>
Example that DOES NOT work (but, no error is thrown):
<Window.Resources>
<DataTemplate x:Key="FirstTemplate">
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding ClassId}"></TextBox>
<TextBox Text="{Binding ClassName}"></TextBox>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Path=DataSheet.Item}" Grid.IsSharedSizeScope="True"
HorizontalAlignment="Stretch"
ItemTemplate="{StaticResource ResourceKey=FirstTemplate}"/>
</Grid>
Any advice as to what I am doing wrong would really be appreciated.
Thanks.
Your ItemSource should be a collection meanwhile DataSheet.Item looks like a single item.
You should wrap it into collection.
Or you could manually add ListBoxItem.
<ListBox>
<ListBoxItem Content="{Binding DataSheet.Item}" ContentTemplate="{StaticResource FirstTemplate}"/>
</ListBox>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With