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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With