我想在与DataTemplate关联的上下文菜单中使用CommandParameter属性。 commandParameter应该包含对触发数据模板的对象的引用,如下面的代码示例所示。我试图使用“{Binding Path = this}”,但它不起作用,因为“this”不是属性。该命令触发但我无法获得正确的参数。有没有人知道如何做到这一点?
注意:我删除了Command =“{Binding DeleteSelectedMeetingCommand}”,将其替换为对视图定位器的引用,并且命令正在触发。
<DataTemplate DataType="{x:Type Models:MeetingDbEntry}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=HostTeam}"/>
<TextBlock Grid.Column="1" Text="{Binding Path=GuestTeam}"/>
<TextBlock Grid.Column="2" Text="{Binding Path=Result}"/>
<Grid.ContextMenu>
<ContextMenu Name="MeetingMenu">
<MenuItem Header="Delete"
Command="{Binding
Source={StaticResource Locator},
Path=Main.DeleteSelectedMeetingCommand}"
CommandParameter="{Binding Path=this}"/>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
谢谢,
答案 0 :(得分:3)
它正在使用以下代码。您只需在CommandParameter属性中键入{Binding}即可引用触发DataTemplate的属性。
<DataTemplate DataType="{x:Type Models:MeetingDbEntry}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=HostTeam}"/>
<TextBlock Grid.Column="1" Text="{Binding Path=GuestTeam}"/>
<TextBlock Grid.Column="2" Text="{Binding Path=Result}"/>
<Grid.ContextMenu>
<ContextMenu Name="MeetingMenu">
<MenuItem Header="Delete"
Command="{Binding
Source={StaticResource Locator},
Path=Main.DeleteSelectedMeetingCommand}"
CommandParameter="{Binding}"
/>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
答案 1 :(得分:0)
我会在删除的对象上公开DeleteSelectedMeetingCommand并将上下文菜单项绑定到它。然后添加一个包含要删除的对象的成员变量,并在对象中使用this
对其进行初始化,以删除持有该命令的对象。
示例:
public class DeletableObject
{
public ICommand DeleteCommand { get; }
public DeleteableObject()
{
DeleteCommand = new DeleteCommand(this);
}
}
public class DeleteCommand : ICommand
{
private DeletableObject _DeletableObject;
public DeleteCommand(DeletableObject deletableObject)
{
_DeletableObject = deletableObject;
}
// skipped the implementation of ICommand but it deletes _DeletableObject
}
希望有所帮助。