WPF Thumb 实现rectangle 移动 mvvmlight
时间: 2023-10-09 09:10:17 浏览: 92
要实现WPF Thumb mvvmlight实现Rectangle移动,可以按照以下步骤进行:
1. 在XAML中,定义一个Thumb,将其放置在Rectangle上方,设置Thumb的DragDelta事件处理程序为Thumb_DragDelta,如下所示:
```xml
<Thumb Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}" DragDelta="Thumb_DragDelta"/>
<Rectangle Width="100" Height="100" Fill="Red"/>
```
2. 在ViewModel中,定义Rectangle的坐标属性X和Y,并在构造函数中初始化它们:
```csharp
public class MainViewModel : ViewModelBase
{
private double _x;
private double _y;
public double X
{
get { return _x; }
set { Set(ref _x, value); }
}
public double Y
{
get { return _y; }
set { Set(ref _y, value); }
}
public MainViewModel()
{
X = 100;
Y = 100;
}
}
```
3. 在事件处理程序Thumb_DragDelta中,更新Rectangle的坐标属性X和Y:
```csharp
private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
{
X += e.HorizontalChange;
Y += e.VerticalChange;
}
```
4. 确保ViewModel实现了INotifyPropertyChanged接口,以便在属性更改时通知UI更新。
```csharp
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
```
这样,你就可以使用WPF Thumb mvvmlight实现Rectangle移动了。
阅读全文