gpt4 book ai didi

wpf - 使用相同的 DataContext 设置 DataGrid 和 ContextMenu

转载 作者:行者123 更新时间:2023-12-03 10:35:28 25 4
gpt4 key购买 nike

我正在尝试为传入所选菜单项(Mvvm)的数据网格动态创建上下文菜单。我希望上下文菜单的 DataContext 与网格相同。

我有以下 Xaml

<Grid>
<!-- Cut some other stuff -->
<Border Grid.Row="2" BorderBrush="Black" BorderThickness="1">
<DataGrid x:Name="MyDataGrid" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=GridData}" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="None" SelectionUnit="Cell" SelectionMode="Single">
<DataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextMenuActions}">
<MenuItem Header="{Binding DisplayName}" Command="{Binding Command}" />
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Header="DataOne" Width="130" Binding="{Binding Path=DataOne}"/>
<DataGridTextColumn Header="DataTwo" Width="100" Binding="{Binding Path=DataTwo}"/>
<DataGrid.Columns>
<DataGrid.InputBindings>
<MouseBinding Gesture="RightClick" Command="{Binding DataGridRightClick}" CommandParameter="{Binding ElementName=MyDataGrid, Path=SelectedCells}" />
</DataGrid.InputBindings>
</DataGrid>
</Border>
</Grid>

以及我用于数据网格并且还想用于我的上下文菜单的数据上下文的以下类(为了便于阅读,我已经删除了所有数据网格填充代码)和菜单项
public class DataViewModel : ViewModelBase // Implements INotifyPropertyChanged
{
// All code that populates the grid has been removed

public ObservableCollection<MenuItemViewModel> ContextMenuActions { get; set; }
public ICommand DataGridRightClick { get; private set; }

public MarketDataViewModel()
{
DataGridRightClick = new RelayCommand(RightClick);
}

public void RightClick(object obj)
{
MenuItemViewModel menuItem = new MenuItemViewModel("Test", new RelayCommand(TestCall));
ContextMenuActions.Add(menuItem); // I ensure this is added on the gui thread
MenuItemViewModel menuItem1 = new MenuItemViewModel("Test2", new RelayCommand(TestCall));
ContextMenuActions.Add(menuItem1); // I ensure this is added on the gui thread but for
}

private void TestCall(object obj)
{
// want to pass in the selected menuitem
}
}

public class MenuItemViewModel
{
public MenuItemViewModel(string displayName,ICommand command)
{
DisplayName = displayName;
Command = command;
}

public string DisplayName { get; set; }
public ICommand Command { get; set; }
}

目前,当我单击数据网格时,右键单击事件会被调用并运行良好,但网格上会出现一个空的上下文菜单。

谢谢,
缺口

最佳答案

您需要绑定(bind)到 DataContext.ContextMenuActions parent 的DataGrid .实现此目的的最简单方法是使用以下绑定(bind):

<ContextMenu ItemsSource="{Binding DataContext.ContextMenuActions, ElementName=MyDataGrid}" ... 

关于wpf - 使用相同的 DataContext 设置 DataGrid 和 ContextMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655188/

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