2

UWP / WinRT: How to access a control generated by a model from the element to wh...

 2 years ago
source link: https://www.codesd.com/item/uwp-winrt-how-to-access-a-control-generated-by-a-model-from-the-element-to-which-it-is-linked.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

UWP / WinRT: How to access a control generated by a model from the element to which it is linked?

advertisements

I have a Pivot whose contents are generated using data binding. For each Item in a vector, a Grid is generated, and within each grid a TextBlock is generated.

If I have a particular Item from the vector, how can I access the corresponding TextBlock that was generated from it in my code behind?

My first idea was to set the x:name property for each TextBlock to be a unique identifier held within each Item, and then I could simply call FrameworkElement::FindName() on the identifier, but apparently the x:name property isn't permitted to be generated using data binding.

I see that it's possible to go in the other direction, and pull up the Item from a TextBlock by calling its DataContext.

I'm seeing I could maybe use VisualTreeHelper to start searching for the TextBlock control by control. I'm having trouble locating examples in C++, though, how is this used in this context? Is this the only way to do it? It seems very involved for something so simple. Is there are more ways to do it, what's the correct way to do it?

I'm using C++/CX with XAML.


Pivot is a descendant of ItemsControl, therefore:

Use https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.itemscontrol.containerfromitem.aspx or https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.itemscontrol.containerfromindex.aspx and plus the VisualTreeHelper. (If the ItemTemplate is fixed, you can even do something like ((Grid)*YourReturnedDependencyObject*).Children[0] as TextBlock, so you don't even need the VisualTreeHelper.)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK