所以问题是这样的。我需要设置 Canvas.Top 和 Canvas.Left 的 UserControl,但这些属性是从 ViewModel 绑定的。为简单起见,让我们为用户控件提供此代码,后面没有代码:
<UserControl x:Class="BadBinding.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Canvas.Left="{Binding ElementName=slider, Path=Value}"
>
<Grid Width="100" Background="Red">
<Slider x:Name="slider" Minimum="100" Maximum="250" />
</Grid>
</UserControl>
而这个主窗口的代码:
<Window x:Class="BadBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:BadBinding"
>
<Canvas>
<local:MyUserControl />
</Canvas>
</Window>
我不知道为什么绑定不起作用。当您将 Canvas.Left 直接设置为某个值时,一切都很好,并且将用户控件的内容直接写入主窗口。