views:

30

answers:

2

I am trying to access Control using ElementName from DataTemplate that is used in different UserControl (Resources) than defined (in xaml).

Imagine this situation:

MyUserControl.xaml with following DataTemplate in resources:

<UserControl.Resources>
   <DataTemplate x:Key="SomeTemplate">
      <TextBlock Text="{Binding Text, ElementName=TextElement}"/>
   </DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
    <TextBlock x:Name="TextElement" Text="IT WORKS! (not...)"/>
</Grid>
</UserControl>

MyUserControlWrapper.xaml

<ContentPresenter x:Name="ContentPresenter" Content="{Binding SomeContent}"/>

and in code behind of MyUserControlWrapper.xaml i set ContentTemplate of ContentPresenter from MyUserControl.xaml:

something like:

ContentPresenter.ContentTemplate = (DataTemplate)childView.Resources["SomeTemplate"];

Is it possible to use ElementName from resources that are defined outside UserControl?

How DataTemplate searches for ElementName in same UserControl then? Maybe its possible to set something like DataContext for DataTemplate itself for ElementName to work, without messing with DataContext that is sent to controls used inside Template?

A: 

You need to review the concepts related to Namescopes.

Briefly names are scoped at the point where a Xaml resources are loaded. For example each UserControl will each load their own Xaml and therefore have their own namescope. In your case you asking MyUserControlWrapper to find a name that its LoadComponent has not seen.

AnthonyWJones
Is there a way to assign/set Namescope of any control to DataTemplate from code-behind?
Kestutis
A: 

Maybe you can just walk up the VisualTree using RelativeSource and FindAncestor? There is a nice presentation of different binding variants here: http://www.wpfwiki.com/Default.aspx?Page=WPF%20Q5.3&amp;AspxAutoDetectCookieSupport=1

Simpzon