Jay*_*Jay 14 wpf xaml datagrid contextmenu
我有一个可能有很多行的数据网格.当用户右键单击其中一行时,我需要显示每个行的上下文菜单,并在用户单击该选项时执行操作(根据当前所选行执行相同操作但不同的数据项).
这是什么最好的策略?
我担心每行的ContextMenu都是矫枉过正的,即使我正在使用ContextMenuOpening事件创建菜单,这对于上下文菜单来说是一种"延迟加载".我应该只为数据网格使用一个ContextMenu吗?但是有了这个,我会对click事件有更多的工作,以确定正确的行等.
vor*_*olf 35
据我所知,一些动作将被禁用或启用取决于行,所以没有点单ContextMenu了DataGrid.
我有一个行级上下文菜单的示例.
<UserControl.Resources>
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit" Command="{Binding EditCommand}"/>
</ContextMenu>
<Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
</Style>
</UserControl.Resources>
<DataGrid RowStyle="{StaticResource DefaultRowStyle}"/>
Run Code Online (Sandbox Code Playgroud)
在DataGrid必须有一个绑定到视图模型与命令的列表:
public class ItemModel
{
public ItemModel()
{
this.EditCommand = new SimpleCommand
{
ExecuteDelegate = _ => MessageBox.Show("Execute"),
CanExecuteDelegate = _ => this.Id == 1
};
}
public int Id { get; set; }
public string Title { get; set; }
public ICommand EditCommand { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
上下文菜单是在资源集合中创建的UserControl,我认为只有一个对象通过引用与datagrid行连接,而不是通过值.
这是ContextMenu一个Command内部的另一个例子MainViewModel.我认为DataGrid有一个正确的视图模型DataContext,CommandParameter属性也必须放在Command属性之前:
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit" CommandParameter="{Binding}"
Command="{Binding DataContext.DataGridActionCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
</ContextMenu>
Run Code Online (Sandbox Code Playgroud)
楷模:
public class MainViewModel
{
public MainViewModel()
{
this.DataGridActionCommand = new DelegateCommand<ItemModel>(m => MessageBox.Show(m.Title), m => m != null && m.Id != 2);
}
public DelegateCommand<ItemModel> DataGridActionCommand { get; set; }
public List<ItemModel> Items { get; set; }
}
public class ItemModel
{
public int Id { get; set; }
public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是MenuItem如果CanExecute返回false ,则存在未显示为禁用项的问题.可能的解决方法是使用ParentModel内部的属性ItemModel,但它与第一个解决方案没有太大差别.以下是上述解决方案的示例:
public class ItemModel
{
public int Id { get; set; }
public string Title { get; set; }
public MainViewModel ParentViewModel { get; set; }
}
//Somewhere in the code-behind, create the main view model
//and force child items to use this model as a parent model
var mainModel = new MainViewModel { Items = items.Select(item => new ItemViewModel(item, mainModel)).ToList()};
Run Code Online (Sandbox Code Playgroud)
XAML中的MenuItem将更简单:
<MenuItem Header="Edit" CommandParameter="{Binding}"
Command="{Binding ParentViewModel.DataGridActionCommand}" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28416 次 |
| 最近记录: |