Nehmen wir an, ich habe eine ListView mit einem ContextMenu. Ich möchte es als separate Steuerung namens ListViewWithContextMenu verwenden. Wie kann ich die Befehlsbindungen von ContextMenu so umleiten, dass sie in ListViewWithContextMenu sichtbar sind?Wie Bindings auf "außerhalb" eines XAML-Steuerelements umgeleitet werden
Beispielcode:
ListViewWithContextMenu.xaml
<ListView x:Class="WpfApplication4.ListViewWithContextMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication4"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ListViewWithContextMenu}}, Path= PreviewCommand}" />
</ContextMenu>
</ListView.ContextMenu>
ListViewWithContextMenu.xaml.cs
using System.Windows;
using System.Windows.Input;
namespace WpfApplication4
{
public partial class ListViewWithContextMenu
{
public ICommand PreviewCommand
{
get { return (ICommand)GetValue(PreviewCommandProperty); }
set { SetValue(PreviewCommandProperty, value); }
}
public static readonly DependencyProperty PreviewCommandProperty =
DependencyProperty.Register("PreviewCommand", typeof(ICommand), typeof(ListViewWithContextMenu));
public ListViewWithContextMenu()
{
InitializeComponent();
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext><local:MainWidnowViewModel></local:MainWidnowViewModel></Window.DataContext>
<Grid>
<local:ListViewWithContextMenu PreviewCommand="{Binding Preview}"></local:ListViewWithContextMenu>
</Grid>
</Window>
MainWindowViewModel.cs
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
namespace WpfApplication4
{
public class MainWidnowViewModel
{
public MainWidnowViewModel()
{
Preview = new DelegateCommand(PreviewMethod);
}
private void PreviewMethod()
{
MessageBox.Show("PREVIEW");
}
public ICommand Preview { get; set; }
}
}
Dieser Code die PreviewMethod in Ansichtsmodell nicht nennen, die ich
Ich habe eine Lösung für Ihr Problem. Geben Sie mir einen Moment, um es als Antwort zu schreiben ... –