Get linked object from control

I have the following haml:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding Name}"></Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In my code, I have an event that gives me access to a button. How can I take a button object and get the object to which the name is attached?

Here is the psudo code I would like to work:

public void MyEvent(Object obj)
{
   Button myButton = (Button) obj;
   MyBoundClass myObject = GetBoundClassFromProperty(myButton.Name);

   // Do something with myObject.
}
+3
source share
1 answer

Try accessing the DataContext property. This will contain a link to the current item to which the button is bound.

public void MyEvent(Object obj) 
{ 
   Button myButton = (Button) obj; 
   MyBoundClass myObject = myButton.DataContext as MyBoundClass;

   // Do something with myObject. 
} 
+15
source

Source: https://habr.com/ru/post/1730809/


All Articles