gpt4 book ai didi

c# - 菜单项绑定(bind) WPF 问题

转载 作者:行者123 更新时间:2023-11-30 18:25:09 24 4
gpt4 key购买 nike

我对菜单项命令绑定(bind)有疑问。我使用了 MVVM 模式当我使用右键单击时,会出现菜单。但是当我点击菜单项时不起作用。你知道为什么吗?谢谢

这是 XAML:

    <UserControl x:Class="PlotView.ViewModel.PlotViewControl"
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"
xmlns:oxy="http://oxyplot.org/wpf"
mc:Ignorable="d"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
d:DesignHeight="400" d:DesignWidth="600"
x:Name="theViewName">

<UserControl.Resources>
</UserControl.Resources>

<GroupBox Name="GB" Header="Graphs" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="0">
<ListView Name="PlotLista" SelectedIndex="{Binding SelectedValue}" ItemsSource="{Binding PlotModelList}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ListView.ItemTemplate>
<DataTemplate>
<oxy:Plot MinHeight="260" Height="Auto" IsRendering="True" FontStyle="Normal" FontFamily="Arial" FontSize="8" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=ActualWidth}" Model="{Binding }">
<oxy:Plot.ContextMenu>
<ContextMenu>
<MenuItem Header="Export to PNG" Command="{Binding DataContext.SavePNG, ElementName=theViewName}"/>
</ContextMenu>
</oxy:Plot.ContextMenu>
</oxy:Plot>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</GroupBox>
</UserControl>

这里是 ViewModel 的一小部分:

 #region Fields
private readonly DelegateCommand _menuClick=new DelegateCommand(this.MenuItemClick);
#endregion

#region Command
public ICommand SavePNG
{
get { return this._menuClick; }
}
#endregion

private void MenuItemClick()
{
// some code here
}

错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'SavePNG' property not found on 'object' ''PlotModel' (HashCode=15385318)'. BindingExpression:Path=SavePNG; DataItem='PlotModel' (HashCode=15385318); target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')

最佳答案

您的绑定(bind)试图在您的 Item 上找到 SavePNG,而不是在您的 ViewModel 上。

相反,为您的 View 提供一个 x:Name 或名称,并改用以下绑定(bind):

{Binding DataContext.SavePNG, ElementName=theViewName}

关于c# - 菜单项绑定(bind) WPF 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30453797/

24 4 0