MenuItemのコマンドパラメータを親Grid DataContextにバインドするにはどうすればよいですか?MenuItemから親DataGridへのCommandParameterのバインド
私はContextMenuを持つDataGridを持っており、メニュー項目をViewModelコマンドにバインドしますが、コマンドパラメータは常にnullです。
DataGridにTagパラメータを使用してDataContextにアクセスし、目的のコマンドを使用しますが、すべての行のバインディングデータを取得してコマンドパラメータとして使用することができます。
私はすでに多くの答えを見てきましたが、動作する人がいないため、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>
ちょうど1つの質問ですので、私はあなたを助けることができます:コンテキストメニューはDataGrid行のコンテキストにする必要があります。 –
@RodrigoVedovatoはい! – Trxplz0