问题描述
我有以下的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')
这是因为直接在窗口中使用相同的code特别奇怪的作品完美。
It is especially strange since using the same code directly in a Window works flawlessly.
现在我已经通过但设置在code的结合,解决了这个问题,我不知道为什么我的版本不工作,我宁愿一切都在XAML如果可能的话。
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.
谢谢!
推荐答案
我已经注意到,有时上设置窗口绑定使用的ElementName时
/ 用户控件
等申报的顺序很重要。我不知道的原因,但如果你声明的电网
设置之前&LT; UserControl.RenderTransform&GT;
我认为它会工作
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>
这篇关于一个用户控件属性绑定到通过的ElementName其子产生一个绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!