0

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

4

1 回答 1

0

这将是您的 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();
}
于 2012-10-11T22:21:24.430 回答