使用混合SDK事件触发器触发一个带有相关列表视图项MVVM的按钮点击

本文关键字:列表 视图 MVVM 按钮 一个 事件 触发器 SDK 混合 | 更新日期: 2023-09-27 18:08:48

我试图使用事件触发器从Blend触发一个listview项目的按钮单击事件,它应该工作,使项目必须选择相关的行被引用。

My code is…

Public void MyCommand(object obj)
{
    // the tag of this has the search type
    ListViewItem item = obj as ListViewItem;
    // do my dreary domain work...
}

my xaml is…

<ListView ItemsSource="{Binding Path=SystemSetupItems}" 
    SelectedItem="{Binding Selected, Mode=TwoWay}" 
    MinHeight="120" >
    <ListView.View>
    <GridView>
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
        <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" />
        <GridViewColumn>
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <Button  >
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="MouseClick">
                                <i:InvokeCommandAction CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem, AncestorLevel=1}}" Command="{Binding MyCommand}"/>
                            </i:EventTrigger>
                         </i:Interaction.Triggers>
                     </Button>
                 </DataTemplate>
             </GridViewColumn.CellTemplate>
        </GridViewColumn>                        
    </GridView>
    </ListView.View>
</ListView>

但这根本不起作用,或者我可以在xaml按钮定义

中这样做
<GridViewColumn.CellTemplate>
    <DataTemplate>
        <Button Command="{Binding OpenWorkSpaceCommand}" CommandParameter="{Binding Path=Name}" Content="Edit..." DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}"  >                                 
        </Button>
    </DataTemplate>
</GridViewColumn.CellTemplate>

,但这需要listview项之前被选中,这不是我想要的行为

使用混合SDK事件触发器触发一个带有相关列表视图项MVVM的按钮点击

对于我的DataGrid,我使用单元格模板在每个项目上都有一个按钮。每个项目都是一个类型为Meal的对象。在我的Meal.cs文件中,我有一个像这样的事件定义:

public Meal()
{
    RemoveMealCommand = new RelayCommand(() => RemoveMealCommandExecute());
}
public RelayCommand RemoveMealCommand
{
    get;
    set;
}
public delegate void RemoveMealEventHandler(object sender, EventArgs e);
public event RemoveMealEventHandler RemoveMealEvent;
private void RemoveMealCommandExecute()
{
    RemoveMealEvent(this, null);
}

在我的视图模型中,我可以为列表中的每顿饭添加一个处理程序。对于我的xaml按钮,我只是将命令设置为Meal's RelayCommand。

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Command="{Binding Path=RemoveMealCommand}">
                <Image Width="13" Height="13" Source="/Images/delete-icon.png"/>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

现在,当您单击按钮时,Meal负责触发事件,视图模型负责处理它。