【问题标题】:WPF binding in codebehind fails for transformations代码隐藏中的 WPF 绑定无法进行转换
【发布时间】:2010-12-31 07:02:58
【问题描述】:

显示一个矩形并将 Width、Height、Angle 绑定到视图模型类,正如我在 XAML 中所期望的那样

<Rectangle 
  RenderTransformOrigin="0.5,0.5" 
  Fill="Black" 
  Width="{Binding Path=Width, Mode=TwoWay}" 
  Height="{Binding Path=Height, Mode=TwoWay}">
  <Rectangle.RenderTransform>
    <RotateTransform Angle="{Binding Path=Angle, Mode=TwoWay}" />
  </Rectangle.RenderTransform>
</Rectangle>

但是,在代码隐藏中创建矩形时,我可以绑定到高度和宽度,但不能绑定到角度。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  Binding bindH = new Binding("Height");
  bindH.Mode = BindingMode.TwoWay;

  Binding bindW = new Binding("Width");
  bindW.Mode = BindingMode.TwoWay;

  // DOES NOT WORK
  // AND I DID TRY MANY OTHER COMBINATIONS
  Binding bindA = new Binding("Angle");
  bindA.Mode = BindingMode.TwoWay;

  Rectangle r1 = new Rectangle();
  SolidColorBrush myBrush = new SolidColorBrush(Colors.Black);
  r1.Fill = myBrush;
  r1.RenderTransformOrigin = new Point(0.5,0.5);
  r1.SetBinding(Rectangle.WidthProperty, bindW);
  r1.SetBinding(Rectangle.HeightProperty, bindH);

** // 不工作**

  r1.SetBinding(RenderTransformProperty, bindA);

  LayoutPanel.Children.Add(r1);                     // my custom layout panel
}

感谢所有帮助。

【问题讨论】:

标签: wpf xaml binding code-behind


【解决方案1】:

ViewModel 中的 Angle 属性必须公开为 RotateTransform。 VM 的简单实现如下所示:

public class ViewModel
{
    public RotateTransform Angle { get; set; }
    public int Height { get; set; }
    public int Width { get; set; }

    public ViewModel()
    {
        Angle = new RotateTransform(10);
        Height = 50;
        Width = 100;
    }
}

然后绑定完全按照您在 Window_Loaded 事件处理程序中编写的那样工作。这是有道理的,因为在工作 XAML 版本中,您在 Rectangle 的 RenderTransform 标记中以声明方式指定一个 RotateTransform 对象。

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    使用 Binding 调用 RotateTransform 的 SetValue 方法不起作用。不知道为什么。但是通过 BindingOperations 是可行的。

     var rotateTransform = new RotateTransform();
     BindingOperations.SetBinding(rotateTransform, RotateTransform.AngleProperty, new Binding("RotationAngle") { Source = myViewModel });
     myControl.RenderTransform = rotateTransform;
    

    其中“RotationAngle”是 ViewModel 中的双重属性。

    仅供参考,从 XAML 绑定似乎最终会起作用。我一开始遇到了几个绑定错误,然后它工作了......是的,我的 DataContext 在创建具有 RotateTransform 的对象之前就已经到位。为了避免 Binding 错误,我使用了代码隐藏并在 Loaded 事件期间设置了 Binding。

    【讨论】:

      【解决方案3】:

      您在 Rectangle 上设置 Angle,但您必须在 RotateTransform 上设置 Angle。

      试试这个,

      RotateTransform rot = new RotateTransform();
      r1.RenderTransform = rot;
      rot.SetBinding(RotateTransform.AngleProperty, bindA);
      

      【讨论】:

      • RotateTransform 没有名为 SetBinding 的方法。
      猜你喜欢
      • 2010-11-12
      • 2012-07-15
      • 2013-10-17
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多