Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a UserControl property to its child via ElementName results a binding error

Tags:

.net

wpf

xaml

I have the following XAML:

<UserControl x:Class="WpfWindow.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
  <UserControl.RenderTransform>
    <TranslateTransform X="{Binding ElementName=MySlider, Path=ActualWidth}" />
  </UserControl.RenderTransform>
  <Grid>
    <Slider x:Name="MySlider" Canvas.Left="41" Canvas.Top="86" Height="23"  Width="100" Minimum="0" Maximum="100"/> 
  </Grid>
</UserControl>

When I try to use a window with the UserControl inside I get:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MySlider'. BindingExpression:Path=ActualWidth; DataItem=null; target element is 'TranslateTransform' (HashCode=53368240); target property is 'X' (type 'Double')

It is especially strange since using the same code directly in a Window works flawlessly.

For now I've resolved the issue by setting the binding in code, however, I have no idea why my version doesn't work and I'd rather have everything in XAML if possible.

Thanks!

like image 278
VitalyB Avatar asked Feb 20 '11 10:02

VitalyB


1 Answers

I've noticed that sometimes when setting Bindings with ElementName on Window/UserControl etc. the order of declaration is important. I'm not sure of the reason for this but if you declare the Grid before you set <UserControl.RenderTransform> I think it'll work

<UserControl ...>
    <Grid Background="Red">
        <Slider x:Name="MySlider" Canvas.Left="41" Canvas.Top="86" Height="23"  Width="100" Minimum="0" Maximum="100"/>
    </Grid>
    <UserControl.RenderTransform>
        <TranslateTransform X="{Binding ElementName=MySlider, Path=ActualWidth}" />
    </UserControl.RenderTransform>
</UserControl>
like image 54
Fredrik Hedblad Avatar answered Nov 15 '22 09:11

Fredrik Hedblad