Peppermintology
Peppermintology

Reputation: 10210

XAML nested DataTemplate data-binding

I have an ItemsControl which has its ItemsSource set with a Binding to an ObservableCollection on my ViewModel. I am using a Button control within its ItemTemplate to display my data and I am using a DataTemplate within the Button and none of the Binding data is being displayed. Below is the XAML in question:

<ItemsControl ItemsSource="{Binding Path=ConnectedInstruments}" HorizontalAlignment="Left">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Height="60" VerticalAlignment="Top">
                <Button.ContentTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=ModelCode}" />
                            <TextBlock Text="{Binding Path=SerialNumber}" />
                        </StackPanel>
                    </DataTemplate>
                </Button.ContentTemplate>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Neither TextBlock controls within the Button DataTemplate are being populated. I understand this has something to do with the Binding path, however I am at a loss as to what I am doing wrong. Can someone put me on the right track please?

EDIT

public class Instrument
{
    public string ModelCode { get; set; }
    public string SerialNumber { get; set; }
}

public class ViewModel
{
    public ObservableCollection<Instrument> ConnectedInstruments { get; set; }
}

I know that the ItemsControl is Binding correctly with the ObservableCollection as the correct count of Button controls are being displayed, only the templated data is missing.

Upvotes: 1

Views: 1813

Answers (1)

har07
har07

Reputation: 89285

Any specific reason you need to use ContentTemplate instead of directly setting Button's Content like this? :

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button Height="60" VerticalAlignment="Top">
            <StackPanel>
                <TextBlock Text="{Binding Path=ModelCode}" />
                <TextBlock Text="{Binding Path=SerialNumber}" />
            </StackPanel>
        </Button>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Upvotes: 2

Related Questions