1

所以问题是这样的。我需要设置 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 直接设置为某个值时,一切都很好,并且将用户控件的内容直接写入主窗口。

4

2 回答 2

2

我认为它是因为它UserControl是在添加到之前构造的,Canvas并且因为Canvas.Left它是一个附加属性,它可能无法正确解析。

尝试使用Reference绑定。

<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 Source={x:Reference Name=slider}, Path=Value}"
         >
 <Grid Width="100" Background="Red">
    <Slider x:Name="slider" Minimum="100" Maximum="250" />
 </Grid>
</UserControl>

注意:您可能会收到编译警告,但它仍会编译。

但我认为最好的选择是在你的用户控件上创建一个属性来绑定值,这也可以。

于 2012-12-28T23:59:23.380 回答
0

我尝试了很多,Bindings但它也对我有用..所以如果你想去,EventHandler那么下面的解决方法可能会帮助你..

删除Bindings并添加事件处理程序到ValueChanged事件

在您的MyUserControl.xaml

<UserControl x:Class="BadBinding.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid Width="100" Background="Red">
    <Slider x:Name="slider" Minimum="100" Maximum="250" ValueChanged="slider1_ValueChanged" />
 </Grid>
</UserControl>

在您的MyUserControl.xaml.cs

private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
     Canvas.SetLeft(this, slider1.Value);            
}   

我试过这个并为我工作,如果你发现任何问题,请告诉我..

于 2012-12-29T06:52:40.097 回答