如何将ContextMenu添加到ItemsControl,其中:
我跟着this approach。但是,我有一个Command,它从绑定到ItemsControl的ObservableCollection中删除项目。发生这种情况时,会在RelayCommand中抛出异常。在我看来,ContextMenu不是“隐藏”,所以它试图为其命令评估“CanExecute”,但是当项目被删除时,它不能在RelayCommand的CanExecute方法中将参数强制转换为“T”类。
我想知道如何以正确的方式完成我需要的工作。
到目前为止我的实施:
MainViewModel
public class MainViewModel
{
public ObservableCollection<MyContextMenuClass> ContextMenuItems{ get;set; }
public ObservableCollection<MyItemClass> MyItems{ get;set; }
public void AddItem(MyItemClass item)
{
MyItems.Add(item);
}
public void AddContextMenuItem(MyContextMenuClass item)
{
ContextMenuItems.Add(item);
}
public MainViewModel(IList<MyItemClass> myItems, IList<MyContextMenuClass> myContextualMenuItems)
{
MyItems.AddRange(myItems);
ContextMenuItems.AddRange(myContextualMenuItems);
}
public MainViewModel()
{}
}
MyItemClass
public class MyItemClass
{
public string MyText{get;set;}
}
MyContextMenuClass
public class MyContextMenuClass
{
public RecentContextMenuItem()
{}
public string Caption{get;set;}
public RelayCommand<MyItemClass> Command{get;set;}
}
我的UserControl (DataContext = MainViewModel)
<UserControl x:Class="MyNamespace.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style x:Key="CommandMenuItemStyle" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="MenuItem.Header" Value="{Binding Caption}" />
<Setter Property="MenuItem.Command" Value="{Binding Command}" />
<Setter Property="MenuItem.CommandParameter" Value="{Binding PlacementTarget.DataContext,
RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
</Style>
<ContextMenu x:Key="ItemContextMenu" ItemsSource="{Binding ContextMenuItems}"
ItemContainerStyle="{StaticResource CommandMenuItemStyle}"
DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Title}" Margin="20,5,0,5" Foreground="#FF5D5858" FontFamily="Courier" FontSize="15" Grid.ColumnSpan="2" FontWeight="SemiBold"></TextBlock>
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="2" Padding="5,0,0,0">
<ItemsControl x:Name="myItems" ItemsSource="{Binding MyItems}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyText}" /> <!--Simplied this for the example-->
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ContentPresenter}">
<EventSetter Event="ContextMenu.ContextMenuOpening" Handler="Item_ContextMenuOpening"></EventSetter>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</ScrollViewer>
</Grid>
我的UserControl Codebehind
public partial class MyUserControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="RecentView"/> class.
/// </summary>
public MyUserControl()
{
InitializeComponent();
}
private void Item_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var contentPresenter = sender as ContentPresenter;
if (contentPresenter != null)
{
this.Dispatcher.BeginInvoke(new Action<ContentPresenter>(ShowItemContextMenu), new object[] { contentPresenter });
}
}
private void ShowItemContextMenu(ContentPresenter sourceContentPresenter)
{
if (sourceContentPresenter != null)
{
var ctxMenu = (ContextMenu)this.FindResource("ItemContextMenu");
ctxMenu.DataContext = this.DataContext;
if (ctxMenu.Items.Count == 0)
{
sourceContentPresenter.ContextMenu = null;
}
else
{
ctxMenu.PlacementTarget = sourceContentPresenter;
ctxMenu.IsOpen = true;
}
}
}
}
RemoveItemCommand我添加到MainViewModel
new RelayCommand<MyItemClass>(RemoveItem, (param) => true);
private void RemoveItem(MyItemClassitemToRemove)
{
MyItems.Remove(itemToRemove);
}
RelayCommand的CanExecute方法
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
if (parameter == null)
{
return _canExecute.Invoke(default(T));
}
T value;
try
{
value = (T)parameter;
}
catch(Exception exception)
{
Trace.TraceError(exception.ToString());
return _canExecute.Invoke(default(T));
}
return _canExecute.Invoke(value);
}
我在 value =(T)参数; 行中收到错误,因为参数已断开连接且无法将其强制转换为 T
我得到例外:
MyProgram.vshost.exe错误:0:System.InvalidCastException:无法将类型为“MS.Internal.NamedObject”的对象强制转换为“MyItemClass”。 at MyNamespace.RelayCommand`1.CanExecute(Object parameter)in c:\ MyPath \ RelayCommand.cs:line xxx
如果我检查参数,它是一个NamedObject:
- 参数{DisconnectedItem} object {MS.Internal.NamedObject}
- 非公职人员
_name“{DisconnectedItem}”string
问题不在于Exception,它是通过DisconnectedItem到达这一点的事实。这被多次评估。就像ContextMenu在视觉树中永远“永远”一样。
答案 0 :(得分:8)
首先,只需检查null
的参数值:
return parameter == null ? false : _canExecuteMethod((T)parameter);
其次,这是旧的ContextMenu.DataContext
问题:ContextMenu
显示在与UI其余部分不同的可视树中。因此,它无法从主UI可视树中访问DataContext
。因此,我们必须使用一个小技巧将其传递给另一个可视化树。我们之间的联系是ContextMenu.PlacementTarget
property。
从链接页面,此属性
获取或设置ContextMenu在打开时所处的UIElement。
我们可以使用Tag
对象的ContextMenu.PlacementTarget
属性来传递DataContext
。基本上,只需在要设置Tag
的对象上设置ContextMenu
属性即可。尝试这样的事情:
<ItemsControl x:Name="myItems" ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyText}" Tag="{Binding DataContext,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
ContextMenu="{StaticResource ItemContextMenu}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
...
<ContextMenu x:Key="ItemContextMenu" ItemsSource="{Binding ContextMenuItems}"
ItemContainerStyle="{StaticResource CommandMenuItemStyle}"
DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>
就是这样。现在,ContextMenu
中声明的UI元素将可以访问数据绑定到Tag
属性的任何对象。 EventSetter
完全没有必要使用ContextMenu
...如果你知道怎么做就很简单。
答案 1 :(得分:-1)