SL4. Binding to ElementName not working in DataTemplate

There is another headache with the DataTemplate.


Description: Using Silverlight 4, Mvvm, etc. (Standard toolkit for Silverlight LOB application developers).

The list of objects was successfully bound to the DataGrid . One property (nullable bool BoolValue) is responsible for the behavior of the object and is presented in a datagrid with an image, clicking on which changes the visibility of some controls in the LayoutRoot element.

Problem: The problem is that, unfortunately or fortunately, the ElementName binding in the DataTemplate does not see other elements than those that are placed in this template.

Code example:

 <navigation:DataGridTemplateColumn Width="40" CanUserReorder="True" CanUserSort="False"> <navigation:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Border Background="GhostWhite"> <Grid> <Image x:Name="ImageWithTrigger" Grid.Column="1" Margin="10,4,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" Cursor="Hand" Source="images/someImage.png" Stretch="None" Visibility={Binding BoolValue, Converter={StaticResource boolToVisibilityConverter} }> <i.Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <AttachedBehaviors:TrickyBehavior FrameworkElementToHide="{Binding ElementName=FirstControlOutside}" FrameworkElementToShow="{Binding ElementName=SecoundControlOutside}"/> </i:EventTrigger> </i:Interaction.Triggers> </Grid> </Border> </DataTemplate> </navigation:DataGridTemplateColumn.CellTemplate> </navigation:DataGridTemplateColumn> 

In the above example, FrameworkElementToHide and FrameworkElementToShow are always zero.

There are many similar problems and solutions on the Internet, but I have not found a simple and elegant way to solve this problem.

+4
source share
2 answers

please take a look at my answer in this post.

ElementName binding does not work within the DataGrid . For this you need a proxy server. However, the ElementName binding works for regular DataTemplates , for example. ItemTemplate a ListBox etc.

+6
source

[This should be a comment, but I exceeded the allowed number of characters]

I see two ways to solve this problem:

  • inherit from ContentControl ; add the IsShowing (bool) property, which will switch between the two states; in the control template for the new control, make the desired animation to show and hide the content.
  • add a static class that will contain a dictionary for storing links to elements; add an attached property (bool) with PropertyChangedCallback in the metadata - if the new value is true: add the element (to which the property is attached) to the dictionary, if false: remove the element from the dictionary; the key for each item is the name; the behavior will receive two lines, which are the names of the elements and will look for them in the dictionary.

Both methods are not so elegant, but Silverlight ...; -)

+1
source

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


All Articles