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 に答える