小编use*_*266的帖子

带有itemscontrol的WPF MVVM可移动形状

在过去的两天里,我一直坚持一个(简单?)问题.我在互联网上搜索了很多,但我找不到一个能够解决我完全情况的例子(每次遗漏一个方面,这是我自己实现的突破因素).

我想要什么:

创建我自己的WPF控件,它显示一个顶部矩形(或一般实际上是形状)的图像,在缩放和平移时保持固定.此外,这些矩形需要调整大小(尚未完成)并且可以移动(现在就做).

我希望这个控件能够遵循MVVM设计模式.

我有什么:

我有一个带有ItemsControl的XAML文件.这表示动态数量的矩形(来自我的ViewModel).它绑定到我的ViewModel(ObservableCollection)的RectItems.我想将项目渲染为矩形.这些矩形必须由用户使用他的鼠标移动.移动后,它应该在ViewModel中更新我的模型实体.

XAML:

<ItemsControl ItemsSource="{Binding RectItems}">
<ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas IsItemsHost="True">

            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Canvas.Left" Value="{Binding TopLeftX}"/>
        <Setter Property="Canvas.Top" Value="{Binding TopLeftY}"/>
    </Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Rectangle Stroke="Black" StrokeThickness="2" Fill="Blue" Canvas.Left="0" Canvas.Top="0"
           Height="{Binding Height}" Width="{Binding Width}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <i:InvokeCommandAction Command="{Binding ElementName=border,Path=DataContext.MouseLeftButtonUpCommand}" CommandParameter="{Binding}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseLeftButtonDown">
                    <i:InvokeCommandAction Command="{Binding ElementName=border,Path=DataContext.MouseLeftButtonDownCommand}" CommandParameter="{Binding}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseMove">
                    <i:InvokeCommandAction Command="{Binding ElementName=border,Path=DataContext.MouseMoveCommand}" CommandParameter="{Binding}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Rectangle>
    </DataTemplate>
</ItemsControl.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

视图模型:

public class PRDisplayViewModel : INotifyPropertyChanged
{
    private PRModel _prModel; …
Run Code Online (Sandbox Code Playgroud)

wpf xaml itemscontrol mvvm

6
推荐指数
1
解决办法
2021
查看次数

标签 统计

itemscontrol ×1

mvvm ×1

wpf ×1

xaml ×1