当前位置: 动力学知识库 > 问答 > 编程问答 >

wpf - How to display a listbox with the populated items on click of a menu item in XAML/C#

问题描述:

I have a context menu in my XAML file. When I click on this menu item, I want to display a listbox to the user with a list of data populated from a backend call. How can I achieve this? I am a novice in XAML/WPF.

网友答案:

This would be your 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>

and this would be your cs code:

    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;
    }

where MyViewModel is something like:

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

and MyItemClass is something like:

    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("---"));
    }

I forgot to mention command:

public static class MyCommandsClass
{
    public static RoutedCommand MyCommand1 = new RoutedCommand();
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: