繁体   English   中英

单击XAML / C#中的菜单项时如何显示带有填充项的列表框

[英]How to display a listbox with the populated items on click of a menu item in XAML/C#

我的XAML文件中有一个上下文菜单。 当我单击此菜单项时,我想向用户显示一个列表框,其中包含从后端调用中填充的数据列表。 我该如何实现? 我是XAML / WPF的新手。

这将是您的xaml:

<Window x:Class="MyWpfApp.MyWindow"
    xmlns:cmd="clr-namespace:MyWpfApp.MyCommandsNamespace"
    xmlns:vm="clr-namespace:MyWpfApp.MyViewModelsNamespace"
    ...>
    <Window.Resources>
        <DataTemplate x:Key="MyItemTemplate" DataType="{x:Type vm:MyItemClass}">
            <TextBlock Text="{Binding MyItemText}"/>
        </DataTemplate>
    </Window.Resources>
    <Window.CommandBindings>
         <CommandBinding Command="{x:Static cmd:MyCommandsClass.MyCommand1}" Executed="ExecuteMyCommand" CanExecute="CanExecuteMyCommand"/>
    </Window.CommandBindings>

    <Window.ContextMenu>
        <ContextMenu>
        <MenuItem Header="MyMenuItem1" 
              CommandTarget="{Binding}"
              Command="{x:Static cmd:MyCommandsClass.MyCommand1}"/>
        </ContextMenu>
    </Window.ContextMenu>
    <Grid>
        <ItemsControl ItemsSource="{Binding MyList}"
            ItemTemplate="{StaticResource MyItemTemplate}"/>
    </Grid>
</Window>

这将是您的CS代码:

    public MyWindow()
    {
        VM = new MyViewModelsNamespace.MyViewModel();
        this.DataContext = VM;
        InitializeComponent();
    }
    public void ExecuteMyCommand(object sender, ExecutedRoutedEventArgs e)
    {
        VM.MyList.Add(new MyItemClass{MyItemText="some text"});
    }
    public void CanExecuteMyCommand(object sender, CanExecuteRoutedEventArgs e)
    {
        if (...) e.CanExecute = false;
        else e.CanExecute = true;
    }

MyViewModel是这样的:

    public class MyViewModel : DependencyObject
    {
        //MyList Observable Collection
        private ObservableCollection<MyItemClass> _myList = new ObservableCollection<MyItemClass>();
        public ObservableCollection<MyItemClass> MyList { get { return _myList; } }
    }

和MyItemClass是这样的:

    public class MyItemClass : DependencyObject
    {
        //MyItemText Dependency Property
        public string MyItemText
        {
            get { return (string)GetValue(MyItemTextProperty); }
            set { SetValue(MyItemTextProperty, value); }
        }
        public static readonly DependencyProperty MyItemTextProperty =
            DependencyProperty.Register("MyItemText", typeof(string), typeof(MyItemClass), new UIPropertyMetadata("---"));
    }

我忘了提到命令:

public static class MyCommandsClass
{
    public static RoutedCommand MyCommand1 = new RoutedCommand();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM