Here’s my situation:
I have a Data Template set up which contains a ToggleButton (its purpose is to represent the underlying type as a button the user can interact with).
My whole usercontrol is a stackpanel that scrolls as new buttons are added to it. Every time a new button is added, it is hosted by a ContentControl and then added to the stack panel’s children. Something like this:
var newButton = new DataType();
var host = new ContentControl {content = newButton};
stackPanel.Children.Add(host);
Where DataType is the type that the DataTemplate is looking for.
This DataType class has a property which I need access to in the code behind.
When a user clicks on one of these toggle buttons, I want to be able to get a reference to the DataType object that the button represents, and I cannot figure out how to do this. Is it possible?
Any help would be greatly appreciated.
If you’re handling a click event of some sort, you probably have a handler like
Sender is going to be your control. You can cast the object to whatever it is, and then access its DataContext, which you can also cast to your “DataType”. If the visual relationship is more compelex, you may need to walk the visual tree more, but you should be able to do this. With a code-behind approach, this is a common way I’ve seen to get at things that are in data templates and thus can’t be named and manipulated directly.