我有一个MenuItem,其中ItemsSource被数据绑定到一个简单的字符串列表,它显示正确,但我很难看到我如何处理它们的点击事件!
这是一个演示它的简单应用程序:
<Window x:Class="WPFDataBoundMenu.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Menu>
<MenuItem Header="File" Click="MenuItem_Click" />
<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" />
</Menu>
</Grid>
Run Code Online (Sandbox Code Playgroud)
using System.Collections.Generic;
using System.Windows;
namespace WPFDataBoundMenu
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public List<string> MyMenuItems { get; set;}
public Window1()
{
InitializeComponent();
MyMenuItems = new List<string> { "Item 1", "Item 2", "Item 3" };
DataContext = this;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("how …
Run Code Online (Sandbox Code Playgroud) 我现在仍在摸索WPF,并且无法弄清楚为什么禁用此上下文菜单项:
<Window x:Class="DisabledMenuItemProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DisabledMenuItemProblem"
Title="Window1" Height="300" Width="300">
<TextBlock Text="fooooobaaaaaar">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Foo" Command="{x:Static local:MyCommands.FooBar}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</Window>
using System.Windows;
using System.Windows.Input;
namespace DisabledMenuItemProblem
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
CommandBindings.Add(new CommandBinding(MyCommands.FooBar, FooExecuted, CanFooExecute));
}
public void FooExecuted(object sender, ExecutedRoutedEventArgs e)
{ MessageBox.Show("Foo!"); }
public void CanFooExecute(object sender, CanExecuteRoutedEventArgs e)
{ e.CanExecute = true; }
}
public static class MyCommands
{
public static RoutedCommand FooBar = new RoutedCommand();
}
} …
Run Code Online (Sandbox Code Playgroud) 对于linq的世界来说还是新手,我需要一些帮助,将有孩子的父母列表整理成一个ParentChild列表.
像这样:
class Program
{
static void Main()
{
List<Parent> parents = new List<Parent>();
parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });
// linq query to return List<ParentChild> parentChildList;
// ParentName = Parent1, ChildName …
Run Code Online (Sandbox Code Playgroud)