Reputation: 3478
I have a user control with ContentObject property and I use it to specify custom content. On my main window I created a nested label bound to a dependency property. It works fine if I bind it with RelativeSource, but for some reason it doesn't work if I reference element by name:
MainWindow.xaml:
<Window x:Class="TestContentPresenter.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestContentPresenter"
Title="MainWindow" Height="350" Width="525" Name="MyWindow">
<Grid>
<local:MyUserControl>
<local:MyUserControl.ContentObject>
<!--<TextBlock Text="{Binding MyText, ElementName=MyWindow}"/>-->
<TextBlock Text="{Binding MyText, RelativeSource={RelativeSource AncestorType=Window}}"/>
</local:MyUserControl.ContentObject>
</local:MyUserControl>
</Grid>
</Window>
UserControl.xaml:
<UserControl x:Class="TestContentPresenter.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestContentPresenter"
Height="300" Width="300" Name="MainControl">
<StackPanel>
<ContentPresenter Content="{Binding ContentObject, ElementName=MainControl}"/>
</StackPanel>
</UserControl>
Main window has MyText dependency property and the commented line is what doesn't work. I suspect that this has something to do with name scopes, but is there anything I'm doing wrong?
Upvotes: 3
Views: 376
Reputation: 169370
No, you are not really doing anything wrong, it's just that the by the time the binding to the TextBlock's Text property gets resolved there is no element named "MyWindow" in scope. You set the ContentObject property of the UserControl to a TextBlock but when the UserControl eventually renders it doesn't know anything about any "MyWindow" name.
You could solve this by simply replacing the ElementName with a RelativeSource - as you have already discovered - since the TextBlock will always have a parent window. ElementName won't work.
Upvotes: 2