Reputation: 16148
I have a fairly complex tree of data which I'm displaying in a WPF UserControl and the control is using DataTemplates to create and link various UI elements up to the various data inside the tree. Here's a (very) simplistic example which involves a list of items being display in an ItemsControl sitting on a canvas, and each element is represented with a TextBox:
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox
Text="{Binding ...}"
Canvas.Left="{Binding ...}"
Canvas.Top="{Binding ...}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
Now an event has occurred inside my UserControl whereby I have a reference to one of the list items and I want to set the focus to the TextBox item behind it. Is there an easy way to get the TextBox element from the data object that its Data Context is bound to? Or do I have to manually walk the entire visual tree myself?
I realize I could put a member inside the data element itself and use triggers to do whatever it is I'm trying to do but in my case it would require an extra layer of abstraction that I'd really like to avoid if at all possible.
Upvotes: 4
Views: 1228
Reputation: 1670
As you say, if you cannot directly add a member to the item class that you are using, I assume its a built-in type you don't have access to, you must create a proper View Model to access a trigger like
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding IsTextBoxFocused}" />
</Trigger>
It's another layer of abstraction but you will always find it important to use a View Model that you have access to.
Upvotes: 2