I can't get DataTemplate to work in WPF

I tried several different ways to get a simple DataTemplate example to work. But I’m out of luck. The data context for XAML below is set in the code. The two code examples shown here are wrapped in an element of my application, but this is the only external consideration. The first code sample works. It displays data. But, if I put the functionality in a DataTemplate and then try to use a template, this will 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>

An example that does NOT work (but no error occurs):

<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 regarding what I am doing wrong will really be appreciated.

Thank.

+3
source share
3 answers

ItemSource , DataSheet.Item . .

ListBoxItem.

<ListBox>
    <ListBoxItem Content="{Binding DataSheet.Item}" ContentTemplate="{StaticResource FirstTemplate}"/>
</ListBox>
+4

, , , DataSheet.Item IEnumerable. IEnumerable ListBox.ItemsSource .

0

Try the following:

  <ListBox ItemsSource="{Binding Path=DataSheet.Item}" Grid.IsSharedSizeScope="True"
             HorizontalAlignment="Stretch"
             ItemTemplate="{StaticResource FirstTemplate}"/>

Here is the link for more information.

-1
source

All Articles