来自C#而不是XAML的ConstrainToParentBounds

来自C#而不是XAML的ConstrainToParentBounds,c#,wpf,xaml,windows-phone-8,C#,Wpf,Xaml,Windows Phone 8,要将XAML中的可拖动对象约束到其父容器,我可以执行以下操作 <Image Name="myImage" Source="Images/MyImage.png"> <i:Interaction.Behaviors> <el:MouseDragElementBehavior ConstrainToParentBounds="True"/> </i:Interaction.Behaviors> </Image>

要将XAML中的可拖动对象约束到其父容器,我可以执行以下操作

<Image Name="myImage" Source="Images/MyImage.png">
    <i:Interaction.Behaviors>
        <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </i:Interaction.Behaviors>
</Image>

这就是从代码中获取行为的方式。您可以更改为返回对象的属性

System.Windows.Interactivity.Interaction.GetBehaviors(myImage)

正如Andras所说,我需要获得行为集合。但是,我还需要添加一个新事件,因为MouseDrageElementBehavior不在行为集合中

BehaviorCollection behaviors = Interaction.GetBehaviors(myImage);
var mouseDragBehavior = new MouseDragElementBehavior();
mouseDragBehavior.ConstrainToParentBounds = true;
behaviors.Add(mouseDragBehavior);
BehaviorCollection behaviors = Interaction.GetBehaviors(myImage);
var mouseDragBehavior = new MouseDragElementBehavior();
mouseDragBehavior.ConstrainToParentBounds = true;
behaviors.Add(mouseDragBehavior);