2023-7-27WPF的ContextMenu的传参绑定方式

WPF的ContextMenu的绑定方式

【作者】长生

ContextMenu为何不能正常绑定

在wpf中ContextMenu和ToolTip一样都是弹出层,与VisualTree已经分离了,只不过ToolTip在wpf中有进行特殊处理,所以可以正常绑定。


个人觉得ContextMenu绑定的最可靠的方式

  1. 首先添加BindingProxy类,继承Freezable,Freezable权限很高,可以实现可靠的数据绑定。
  2. 添加依赖属性object,方便传值。
    public class BindingProxy : Freezable
    {
        protected override Freezable CreateInstanceCore()
        {
            return new BindingProxy();
        }

        public object Data
        {
            get { return (object)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new PropertyMetadata(null));
    }
  1. 在xaml页面资源中添加命名空间,并添加控件绑定
xmlns:viewModel="clr-namespace:xxxxxxx"

<UserControl.Resources>
	<viewModel:BindingProxy x:Key="runRecordList" Data="{Binding ElementName=runRecordList}" />//绑定到需要传值的控件
</UserControl.Resources>
  1. 在Context将改控件绑定到CommandParameter,即可对其进行传参。当然也可以直接绑定到ContextMenu上的DataContext,这样就可以直接对Command和ComandParameter进行绑定,再次我就不一一列举了。
 <DataGrid.ContextMenu>
 	<ContextMenu>
 	 <MenuItem
 		Command="{Binding OpenCommand}"CommandParameter="{Binding Source={StaticResource runRecordList}, Path=Data.SelectedItem}"Header="打开" />
	</ContextMenu>
</DataGrid.ContextMenu>
  1. 当然也可以引用外部资源DiscreteObjectKeyFrame进行绑定,方法和上述类似

使用PlacementTarget

在WPF中,PlacementTarget是一个属性,用于指定弹出式控件(如ContextMenu、ToolTip等)的放置目标。它定义了弹出式控件相对于哪个元素进行定位和显示。
PlacementTarget属性通常用于设置弹出式控件的放置位置。例如,当使用ContextMenu时,可以将ContextMenu的PlacementTarget属性设置为一个控件,以便在该控件上右键单击时显示ContextMenu。这样,ContextMenu将相对于该控件进行定位并显示。

  <ListBox.ContextMenu>
 	<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
		<MenuItem Command="{Binding DeleteCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem.Id}" Header="删除" />
	</ContextMenu>
</ListBox.ContextMenu>

结尾

感谢您的阅读,如果有收获麻烦点个关注!⭐
其他平台
公众号:【长生小殿】
B站:【月长生殿主】

posted @ 2023-07-27 17:54  月长生  阅读(747)  评论(0编辑  收藏  举报