开发者

Get a Bound Object from a control

开发者 https://www.devze.com 2022-12-18 11:32 出处:网络
I have the following xaml: <ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate> <Button Content=\"{Binding Name}\"></Button>

I have the following xaml:

<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 the button. How can I take the button object and get the object that it's Name is bound to?

Here is psudo code that I would like to work:

public void MyEvent(Object obj)
{
   Button myButton = (But开发者_如何学Cton) obj;
   MyBoundClass myObject = GetBoundClassFromProperty(myButton.Name);

   // Do something with myObject.
}


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

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

   // Do something with myObject. 
} 
0

精彩评论

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

关注公众号