[英]How do you reference the matching object from a DataTemplate in XAML?
我想在与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>
谢谢,
它正在使用下面的代码。 您只需在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>
我将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
}
希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.