我已将自定义拖动行为添加到网格上的TextBlock
XAML
<Grid>
<TextBlock Text="{Binding Description}" >
<i:Interaction.Behaviors>
<flowfieldVisualiser:DragBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
</Grid>
行为代码
public class DragBehavior : Behavior<UIElement>
{
private Point _elementStartPosition;
private Point _mouseStartPosition;
private readonly TranslateTransform _transform = new TranslateTransform();
protected override void OnAttached()
{
AssociatedObject.RenderTransform = _transform;
AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
AssociatedObject.MouseMove += AssociatedObject_MouseMove;
}
void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var parent = Application.Current.MainWindow;
_elementStartPosition = AssociatedObject.TranslatePoint(new Point(), parent);
var vector = e.GetPosition(parent) - _elementStartPosition;
_mouseStartPosition = new Point(vector.X, vector.Y);
AssociatedObject.CaptureMouse();
}
void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
var parent = Application.Current.MainWindow;
_elementStartPosition = AssociatedObject.TranslatePoint(new Point(), parent);
var diff = e.GetPosition(parent) - _mouseStartPosition;
if (AssociatedObject.IsMouseCaptured)
{
_transform.X = diff.X;
_transform.Y = diff.Y;
}
}
void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
AssociatedObject.ReleaseMouseCapture();
}
}
这很好用,我可以拖动文本框。问题是,我需要知道我的datacontext中的新值是什么。如何将TranslateTransform x和y绑定到我的数据上下文的x和y属性?
答案 0 :(得分:0)
这是一个示例
Binding bindingX = new Binding("DataContext.X");
bindingX.Source = AssociatedObject;
bindingX.Mode = BindingMode.OneWayToSource;
BindingOperations.SetBinding(_transform, TranslateTransform.XProperty, bindingX);
假设DataContext
视图模型在代码上面有一个名为X
的属性,将为TranslateTransform.XProperty
的_transform设置一个绑定,这将把值推送到源绑定,即AssociatedObject的DataContext.X。因此将值推送到VM的属性。
您可能还需要为Y属性设置相同的内容。
信息UIElement
没有DataContext,因此除非AssociatedObject的类型为FrameworkElement
,否则可能无法正常工作。
您也可以将其更改为Behavior<FrameworkElement>
以获得更好的可靠性