【问题标题】:How to display a listbox with the populated items on click of a menu item in XAML/C#如何在 XAML/C# 中单击菜单项时显示带有填充项的列表框
【发布时间】:2012-10-11 21:30:16
【问题描述】:

我的 XAML 文件中有一个上下文菜单。当我单击此菜单项时,我想向用户显示一个列表框,其中包含从后端调用填充的数据列表。我怎样才能做到这一点?我是 XAML/WPF 的新手。

【问题讨论】:

  • 1.你厌倦了哪些项目? 2.此上下文菜单附加到什么? 3. 你使用的是 MVVM 模式吗? 3.你想在哪里显示列表框?在屏幕上还是在弹出窗口上? 5. 物品清单有多长? 6. 你希望在不同的线程上加载数据吗?还有很多问题!

标签: c# wpf xaml


【解决方案1】:

这将是您的 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();
}

【讨论】:

  • 希望这会有所帮助。顺便说一句,我忘了提到命令声明。我已将其添加到答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多