user1005448
user1005448

Reputation: 637

Datatemplate get contents of child controls

I got a datatemplate

<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <ui:UniformWrapPanel />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Border  MouseUp="ItemBorder_MouseUp"  Name="ItemBorder" CornerRadius="10" BorderBrush="Black" BorderThickness="1" Margin="3" Background="{Binding Converter={StaticResource RescuerColorConverter}}">
            <StackPanel Orientation="Vertical" Margin="3">
                <TextBlock FontWeight="Bold" FontSize="20" Text="{Binding Path=Identifier}" HorizontalAlignment="Center" />
                <TextBlock FontSize="16" Text="{Binding Converter={StaticResource RescuerNameConverter}}" HorizontalAlignment="Center" />
            </StackPanel>
        </Border>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Which displays a list of people and their identifiers:

+--------+
|  6969  |
|  Name  |
+--------+

I can get the event from the box if i set MouseUp on the Border control but how do I get the values from the textblocks ?

Thanks.

Upvotes: 0

Views: 620

Answers (2)

Matthew Walton
Matthew Walton

Reputation: 9969

The event handler has a 'sender' parameter which is the object with which the event originated. This will let you get your hands on the instance of Border that you want. Then there are two possibilities:

1) if you're using data binding, the Border's DataContext should be the item for which the DataTemplate was created.

2) if you're not using data binding, you can dig into the visual tree of the Border and locate the TextBlocks that way.

Personally I'd really prefer option 1, however I tend to use neither as I would wire up this kind of thing using Caliburn Micro's actions which let me pass the datacontext as a parameter to a method on the ViewModel.

Upvotes: 2

brunnerh
brunnerh

Reputation: 185489

The DataContext is the object which holds the data, otherwise the bindings would not work, just cast it and get what you need.

var data = (MyDataClass)(sender as Border).DataContext;
// Do stuff with data.Identifier etc.

Upvotes: 1

Related Questions