codebehind中的WPF绑定无法进行转换
显示一个矩形,并将宽度、高度和角度绑定到视图模型类,正如我在XAML中所期望的那样codebehind中的WPF绑定无法进行转换,wpf,xaml,binding,code-behind,Wpf,Xaml,Binding,Code Behind,显示一个矩形,并将宽度、高度和角度绑定到视图模型类,正如我在XAML中所期望的那样 <Rectangle RenderTransformOrigin="0.5,0.5" Fill="Black" Width="{Binding Path=Width, Mode=TwoWay}" Height="{Binding Path=Height, Mode=TwoWay}"> <Rectangle.RenderTransform> <Rot
<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>
**//不起作用**
r1.SetBinding(RenderTransformProperty, bindA);
LayoutPanel.Children.Add(r1); // my custom layout panel
}
感谢您的帮助。您在ViewModel中的Angle属性必须以旋转变换形式显示。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;
}
}
然后,绑定的工作方式与您在窗口加载的事件处理程序中编写的完全相同。这是有意义的,因为在工作的XAML版本中,可以在矩形的RenderTransform标记中声明性地指定RotateTransform对象
希望这有帮助:)您正在矩形上设置角度,但必须在旋转变换上设置角度 试试这个
RotateTransform rot = new RotateTransform();
r1.RenderTransform = rot;
rot.SetBinding(RotateTransform.AngleProperty, bindA);
使用绑定调用RotateTransform的SetValue方法无效。不知道为什么。但通过绑定操作是可行的
var rotateTransform = new RotateTransform();
BindingOperations.SetBinding(rotateTransform, RotateTransform.AngleProperty, new Binding("RotationAngle") { Source = myViewModel });
myControl.RenderTransform = rotateTransform;
其中“RotationAngle”是ViewModel中的双重属性
仅供参考,XAML的绑定似乎最终会起作用。我一开始遇到了几个绑定错误,然后它就开始工作了……是的,我的DataContext在创建RotateTransform对象之前就已经就位了。为了避免绑定错误,我求助于代码隐藏,并在加载的事件期间设置绑定。RotateTransform没有名为SetBinding的方法。这有助于我:
var rotateTransform = new RotateTransform();
BindingOperations.SetBinding(rotateTransform, RotateTransform.AngleProperty, new Binding("RotationAngle") { Source = myViewModel });
myControl.RenderTransform = rotateTransform;