gpt4 book ai didi

wpf - 将 WPF ContextMenu 子菜单绑定(bind)到集合

转载 作者:行者123 更新时间:2023-12-04 05:21:11 24 4
gpt4 key购买 nike

尝试获取要绑定(bind)到 ObservableCollection 的子菜单项列表。

我可以让绑定(bind)在顶级菜单上工作。如果我在代码中添加它们,我也可以在子菜单中显示这些项目,我想避免这种情况。

MainWindow.xaml:

    <ContextMenu x:Key="tbMenu" >

<-- Top level menu item -->
<MenuItem Name="menuLaunchJob" Header="Launch a Job" >
<-- Display a list of the available jobs in a submenu -->
<MenuItem.ItemTemplate> <-- This doesn't work -->
<DataTemplate>
<MenuItem ItemsSource="{Binding}" Header="{Binding jobName}" />
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>

<-- Top level menu item -->
<MenuItem Name="menuEditJobs" Header="Edit Jobs" >
</ContextMenu>

<!-- Globally declared notify icon -->
<tb:TaskbarIcon x:Key="StatusIcon"
MenuActivation="LeftOrRightClick"
ContextMenu="{StaticResource tbMenu}" />

MainWindow.xaml.cs:
public partial class MainWindow : Window
{
private static TaskbarIcon mTaskBar = null;

public MainWindow()
{
JobsClass jc = new JobsClass();

Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
InitializeComponent();
mTaskBar = (TaskbarIcon)this.FindResource("StatusIcon");

// Job sub-menu list is always the 1st item in the main menu
MenuItem launchJob = (MenuItem)mTaskBar.ContextMenu.Items[0];
launchJob.DataContext = jc.mJobs;
}

public class JobsClass
{
private static JobConfig mJobConfig = JobConfig.Instance;
public ObservableCollection<JobConfig.JobData> mJobs = new ObservableCollection<JobConfig.JobData>();

public JobsClass()
{
mJobConfig.ReadJobs();
foreach (JobConfig.JobData job in mJobConfig.GetJobs())
{
mJobs.Add(job);
}
}
}
}

最佳答案

试试这个:

    <-- Top level menu item -->
<MenuItem Name="menuLaunchJob" Header="Launch a Job" ItemsSource="{Binding}" DisplayMemberPath="jobName">

(假设您的 {Binding} 设置为您的 ObservableCollection)

关于wpf - 将 WPF ContextMenu 子菜单绑定(bind)到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675066/

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