开发者

How to attach an object to an event in C#/.NET?

开发者 https://www.devze.com 2023-01-21 22:18 出处:网络
I defined the following DataTemplate for a LibraryContainer: <DataTemplate x:Key=\"ContainerItemTemplate\">

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 开发者_StackOverflow社区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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消