[英]ConstrainToParentBounds from C# instead of XAML
To constrain a draggable object in XAML to its parent container I can do the following. 要将XAML中的可拖动对象限制到其父容器,我可以执行以下操作。
<Image Name="myImage" Source="Images/MyImage.png">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Image>
How would I do this in C#? 我将如何在C#中执行此操作? My best guess which appears to be incorrect was: 我最好的猜测似乎是不正确的是:
myImage.SetValue(MouseDragElementBehavior.ConstrainToParentBoundsProperty, true);
This is how you get the behaviors from code. 这就是您从代码中获得行为的方式。 You can change to property on the returned object. 您可以更改返回对象的属性。
System.Windows.Interactivity.Interaction.GetBehaviors(myImage)
As Andras stated, I needed to get the behavior collection. 正如Andras所说,我需要获取行为集合。 However, I also needed to add a new event since the MouseDrageElementBehavior was not already in the behavior collection. 但是,由于行为集合中还没有MouseDrageElementBehavior,因此我还需要添加一个新事件。
BehaviorCollection behaviors = Interaction.GetBehaviors(myImage);
var mouseDragBehavior = new MouseDragElementBehavior();
mouseDragBehavior.ConstrainToParentBounds = true;
behaviors.Add(mouseDragBehavior);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.