如何使用WPF路径对象保持MVVM模式单击



在WPF应用程序上,我得到了一个包含多个路径对象的帆布对象。我需要在单击那些路径上做事,即VM中的事物。路径上没有命令,例如按钮。最好的方法是什么?到目前为止,我的解决方案是:

  1. 在后面的视图代码上创建一个Mousedown处理程序以捕捉我的路径
  2. 从此处发送消息
  3. 在目标VM上注册此消息类型,以执行我的业务代码。

对我来说似乎有点过分,您有什么看法?您看到了一种更加严格的方法吗?

非常感谢!

您可以将ButtonPath一起使用为Template

<Button Command="{Binding MyCommand}">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Path ... />
        </ControlTemplate>
    </Button.Template>
</Button>

只是为了添加有关我的最后一个评论的互补信息...定位itemTemplate的正确方法是在itemscontrol.itemcontainerstyle中为contentpresenter造型。下面您会找到我的最后工作代码:

<UserControl.Resources>
    <Style x:Key="PathStyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Path Data="{Binding Data}" 
                          StrokeStartLineCap="Round" 
                          Stretch="Fill" 
                          StrokeEndLineCap="Round" 
                          Stroke="{DynamicResource selectedZoneBorderColor}" 
                          StrokeLineJoin="Round" 
                          Width="{Binding Path=Width}"
                          Height="{Binding Path=Height}"
                          Fill="{DynamicResource selectedZoneColor}" 
                          Panel.ZIndex="1" 
                          StrokeThickness="3" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>
<ItemsControl Name="zonesContainer" ItemsSource="{Binding Zones}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Grid.Column="1" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button 
                            Style="{StaticResource ResourceKey=PathStyle}"
                            Command="{Binding ElementName=zonesContainer, 
                                                Path=DataContext.ActivateZone}"
                            CommandParameter="{Binding Id}"
                        />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left" Value="{Binding Path=Left}" />
                        <Setter Property="Canvas.Top" Value="{Binding Path=Top}" />
                    </Style>
                </ItemsControl.ItemContainerStyle>
            </ItemsControl>

所有这一切都与相应的VM公开了一个观察力的collection,一个区域类暴露了所有内部道具(宽度,高度,顶部,左...)。

您可以在此处确定答案

最新更新