gpt4 book ai didi

c# - 将 MenuItem 的 CommandParameter 绑定(bind)到父 DataGrid

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:20 25 4
gpt4 key购买 nike

如何将命令参数从 MenuItem 绑定(bind)到父 Grid DataContext?

我有一个带有 ContextMenu 的 DataGrid,将菜单项绑定(bind)到 ViewModel 命令,但命令参数始终为 null。

我在 DataGrid 中使用 Tag 参数来访问 DataContext 并使用所需的命令,但我可以弄清楚从每一行获取绑定(bind)数据以用作命令参数。

我已经在这里查看了很多答案,但找不到任何有效的方法,ViewModel 中的命令参数被调用并且命令参数始终为 null。

C#

public class People
{
public int Id { get; set; }
public string Name { get; set; }
}

public class PeopleWindowViewModel
{
public List<People> Peoples { get; set; }

public PeopleWindowViewModel()
{
// populate Peoples list...
}

public ICommand RemoveCommand
{
get
{
return RelayCommand.Create((m) =>
{
// m always null
});
}
}
}

public class PeoplePage : Page
{
public PeoplePage()
{
InitializeComponent();

DataContext = new PeopleWindowViewModel();
}
}

XAML:

  <DataGrid
Margin="0 8 0 8"
d:DataContext="{d:DesignInstance local:People}"
IsReadOnly="True"
ItemsSource="{Binding Peoples}"
Tag="{Binding DataContext,
RelativeSource={RelativeSource AncestorType={x:Type Page}}}">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Id}"
Header="Id" />
<DataGridTextColumn
Binding="{Binding Name}"
Header="Name" />
</DataGrid.Columns>

<DataGrid.ContextMenu>
<ContextMenu
Tag="{Binding Path=PlacementTarget.Tag,
RelativeSource={RelativeSource Self}}">
<MenuItem
Command="{Binding PlacementTarget.Tag.RemoveCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ContextMenu}}"
CommandParameter="{Binding Path=Id,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=DataGrid}}"
Header="Remover" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Page>

最佳答案

我找到了解决方案,但不确定是否有更好的解决方案。不管怎样,你可以这样做:

<DataGrid ItemsSource="{Binding Peoples}">
<DataGrid.Resources>
<ContextMenu x:Key="ctx_menu">
<ContextMenu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="DataContext" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</Style>
</ContextMenu.Resources>
<MenuItem Command="{Binding DataContext.RemoveCommand}"
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
Header="Remove" />
</ContextMenu>
</DataGrid.Resources>

<DataGrid.ItemContainerStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="ContextMenu" Value="{StaticResource ctx_menu}" />
</Style>
</DataGrid.ItemContainerStyle>

</DataGrid>

编辑:这会为您提供整个 People 对象作为 CommandParameter。如果您只想要 Id,只需将 CommandParameter 更改为:

CommandParameter="{Binding PlacementTarget.DataContext.Id, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"

关于c# - 将 MenuItem 的 CommandParameter 绑定(bind)到父 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com