c# - Mvvm在窗口中拖动网格

标签 c# wpf mvvm

我找到了允许在窗口中拖动网格的解决方案。但我正在使用 MVVM。 如何在 MVVM 中完成?我需要使用什么?内容控制还是其他?

<Grid x:Name="grid" Background="Blue" 
  Width="100" Height="100" 
  MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp">
<Grid.RenderTransform>
    <TranslateTransform x:Name="tt"/>
</Grid.RenderTransform>

<Window x:Name="window" ...>
<Grid x:Name="grid"...

Point m_start;
Vector m_startOffset;

private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
m_start = e.GetPosition(window);
m_startOffset = new Vector(tt.X, tt.Y);
grid.CaptureMouse();
}

private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (grid.IsMouseCaptured)
{
    Vector offset = Point.Subtract(e.GetPosition(window), m_start);

    tt.X = m_startOffset.X + offset.X;
    tt.Y = m_startOffset.Y + offset.Y;
}
}

private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
grid.ReleaseMouseCapture();
}

最佳答案

这里与 MVVM 无关。如果你想移动东西并从鼠标/窗口获取事件,这只能通过代码隐藏来完成。
MVVM 命令/RelayCommand 用于模型/ View 模型/ View 处理。不适用于鼠标、窗口交互。

你可以使用输入绑定(bind)等等,但基本上你正在做的是正确的方法

关于c# - Mvvm在窗口中拖动网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31533799/

相关文章:

c# - 将 INotifyPropertyChanged 添加到模型?

c# - 执行当前文件夹下的所有.bat文件,执行后删除

c# - 在 WPF 中制作图形的最佳方法是什么? (或者通常也适用于 WPF)

wpf - 我可以使用多重绑定(bind)进行文本搜索吗

c# - 调试一个简单的碰撞处理器

c# - Wpf 应用程序卡住 - 大量内存泄漏之谜

java - 为什么要使用字符串标识符来访问资源数据?

c# - 访问 Windows Azure 中的文件系统

c# - (更有可能)一个非常微妙的行为的迭代器错误?

model - 自动映射器在 MVVM 应用程序中的使用