How does element name binding work?

I remember reading a couple of weeks ago that it sometimes doesnโ€™t work inside templates, and I recently tried to link things in two different windows, and he could not find the name declarations, so I assumed that it was a local class namespace and just connected instead setting the datacontext. However, I am very interested in when I can use the binding name and when I can not, because it is much more convenient when it is possible.

edit: after reading this article, I found this interesting:

โ€œFor this reason, styles and templates define their own XAML names, regardless of where in the object tree where the style or template is applied.โ€

If this is true, does this mean that the Binding ElementName should not work in templates at all? But then I have specific working bindings for ElementName in my templates. This is the most confusing part, why do some bindings accidentally work inside templates, while others do not? It must have some method for trying to resolve the name, even if it is not in the template or the same namescope

+6
source share
1 answer

Basically, you need to be in the same namespace (read this). Most user interface elements are in the same tree using the same namespace, however, there may be gaps and barriers (styles / templates), and if you have abstract objects like DataGrid columns, they have no scope at all names.

I worked with WPF long enough to guess when I would have problems and I know common areas, but I donโ€™t think there is an easy way to tell in all situations.


If this is true, does this mean that the Binding ElementName should not work in templates at all? But then I definitely have working bindings to the ElementName in my templates.

Inside is just fine, it's the same area. The point here is that if you apply the template and they donโ€™t have their own areas, conflicts will arise.

eg.

 <Button/> <Button/> 

If you expand the ControlTemplate , you get something like:

 <Border Name="bd" Background="{TemplateBinding Background}">...</Border> <Border Name="bd" Background="{TemplateBinding Background}">...</Border> 

Obviously, we get a name conflict.

The same goes for DataTemplates in ItemsControls if you specify controls in a template whose name will conflict with the same control instance in the applicable template of other elements.


In another note, you can snap from the inside of the template to the outside, since there can logically be only one instance with this name, or you can give them an excellent priority depending on how to "close" the name area, for example

 <TextBox Name="tb" Text="Test"/> <ItemsControl ItemsSource="ABC"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Text, ElementName=tb}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 
+13
source

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


All Articles