views:

34

answers:

1

I defined the following DataTemplate for a LibraryContainer:

<DataTemplate x:Key="ContainerItemTemplate">
            <Grid>
                <Border BorderThickness="1" BorderBrush="White" Margin="3">
                    <s:SurfaceTextBox IsReadOnly="True" Width="120" Text="{Binding Path=name}" Padding="3"/>
                </Border>
                <s:SurfaceButton Content="Expand" Click="SourceFilePressed"></s:SurfaceButton>
            </Grid>
        </DataTemplate>

The SourceFilePressed is the following:

 private void SourceFilePressed(object sender, RoutedEventArgs e)
        {
            Logging.Logger.getInstance().log(sender.ToString());
            e.Handled = true;
        }

In the method SourceFilePressed who can I get the object that is binded to the SurfaceTextBox that is in the same grid as the pressed button? Can I somehow in the DataTemplate attach this object to the Click-Event?

+1  A: 

If I parsed your question correctly, I think you could do this:

private void SourceFilePressed(object sender, RoutedEventArgs e)
{
    var obj = (sender as FrameworkElement).DataContext;
}

To explain: the sender is the source of the event, so it's the SurfaceButton. It is a FrameworkElement and thus has a DataContext property. The DataContext is an inherited property, so unless you set it explicitly on the SurfaceButton, it will inherit it's DataContext from its parent (the Grid). The DataTemplate's DataContext is the data item it is templating, so you can see that the SurfaceButton will have that same object as its DataContext.

HTH,
Kent

Kent Boogaart
Nice this is working! Can you shortly explain this line?
Roflcoptr
Thanks a lot for the explanation!
Roflcoptr