上下文菜单项命令使用MVVM绑定WPF [英] Context Menu items command binding WPF using MVVM
问题描述
我知道这个问题在许多网站和StackOverFlow中以不同的方式被问过很多次,但是我发现的所有答案都没有帮助我确切地说,我不能理解他们,并在我的应用程序中实现。所以我想到从我的应用程序中添加一些代码,让你的人可以帮助我更好。
I know this question has been asked many times in different ways in many websites and also in StackOverFlow but all the answers I found are not helping me ot to be precise I am not able to understand them and implement in my application. So I thought of putting some code from my application so that you people can help me better.
问题陈述:我使用的是WPF DataGrid。我添加了上下文菜单,我有3个选项剪切,复制,粘贴。我使用MVVM进行开发。我想DataBind这些选项到我的ViewModel中的命令。但我不能这样做。上下文菜单选项没有得到数据绑定!
Problem Statement : I am using a WPF DataGrid. I have added a Context Menu and I have 3 options Cut,Copy,Paste. I am using MVVM for development. I want to DataBind these options to Commands in my ViewModel. But I am unable to do the same. The context menu options are not getting data bound at all !!!
这是XAML中的我的网格代码:
This is my Grid Code in XAML :
<custom:DataGrid
x:Name="DataGrid_Standard"
Grid.Row="1" Grid.Column="1"
AutoGenerateColumns="False"
IsSynchronizedWithCurrentItem="True"
Background="Transparent"
ItemsSource="{Binding FullGridData}"
ItemContainerStyle="{StaticResource defaultRowStyle}"
ColumnHeaderStyle="{StaticResource DefaultColumnHeaderStyle}"
Grid.ColumnSpan="2">
然后我有一个ContextMenu和一个风格的标题元素
Then I have a ContextMenu and a Style for Header Element
<ContextMenu x:Key="columnHeaderMenu">
<MenuItem Command="{Binding CutCommand}"
Header="Test" />
<MenuItem Header="Copy"/>
<MenuItem Header="Paste"/>
</ContextMenu>
<Style TargetType="{x:Type custom:DataGridColumnHeader}" x:Key="DefaultColumnHeaderStyle">
<Setter Property="ContextMenu" Value="{DynamicResource columnHeaderMenu}" >
</Style>
这行代表我的构造函数
public Window1()
{
this.DataContext = new AppData();
}
这段代码放在我的AppData类中:
This code goes in my AppData class:
public class AppData
{
private IList<GridData> fullGridData = new ObservableCollection<GridData>();<br>
public IList<GridData> FullGridData
{
get { return fullGridData; }
set { fullGridData = value; }
}
private DelegateCommand<object> cutCommand;
public DelegateCommand<object> CutCommand
{
get
{
if (cutCommand == null)
{
cutCommand = new DelegateCommand<object>(CutColumn);
}
return cutCommand;
}
}
private void CutColumn(object obj)
{
//some code goes here
}
}
**我想知道我在哪里做错了?为什么DataBinding不会发生?
请帮助我。请给我提供在我现在的代码,我可以实现它的示例代码或修改。 **
** I want to know exactly where am I doing wrong?? Why is the DataBinding not happening?? Please help me regarding this. Please provide me the sample code or modification in my present code from which I can achieve it. **
推荐答案
<MenuItem Header="Cut" Command="{Binding Path=PlacementTarget.DataContext.CutCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
这篇关于上下文菜单项命令使用MVVM绑定WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!