[英]How to call a command from window pop in wpf
如何从窗口调用委托命令。 我在窗口上方显示一个弹出窗口。.弹出窗口具有需要从ViewModel调用DelegateCommand
按钮。
以下是“窗口”>“ MyPopUp.xaml.cs”的代码
public partial class MyPopUp : Window
{
public MyPopUp(){
InitializeComponent();
}
}
以下是ViewModel>> MyPopUpViewModel.cs的代码
public class MyPopUpViewModel: BindableBase
{
public MyPopUpViewModel()
{
AddCommand = new DelegateCommand(AddCommandCall);
}
private void AddCommandCall()
{
/// Command call Code here
}
public DelegateCommand AddCommand { get; private set; }
}
MyPopUp.xaml代码在这里
<Window x:Class="Project"
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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:Project.PopUpControls"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:prism="http://prismlibrary.com/"
mc:Ignorable="d"
Title="Create Levels" Height="700" Width="900"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<Button
Command="{Binding DataContext.AddCommand}"
Content="test"
Margin="0,5,0,0"
FontSize="16"
FontWeight="Normal"
Width="100"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalAlignment="Top"
VerticalContentAlignment="Center"
Foreground="#ffffff"
Background="#4e4e4e"/>
</Grid>
虽然当InitializeComponent();
在MyPopUp.xaml.cs中调用该窗口, DataContext从MyPopUpViewModel.cs中获取所有命令
然后,当单击弹出按钮时...它应该调用命令AddCommand ,但是不会被调用。
让我知道我所缺少的内容或需要添加/更改的内容。
提前致谢。
在wpf上花了很多时间,并尝试了一些替代方法。.我得到了答案Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"
<Grid>
<Button
Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"
Content="test"
Margin="0,5,0,0"
FontSize="16"
FontWeight="Normal"
Width="100"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalAlignment="Top"
VerticalContentAlignment="Center"
Foreground="#ffffff"
Background="#4e4e4e"/>
我在您的代码后面或xaml中没有看到对您的viewmodel的调用。 也许我错了,但对我来说,您需要在codebehind ==> DataContext = new MyPoPupViewModel()之后的InitializeComponent()之后调用!
Xaml通话:
xmlns:local="clr-namespace:YourApplication"
<Window.DataContext>
<local:MyPoPupViewModel/>
</Window.DataContext>
请为视图设置DataContext
InitializeComponent();
DataContext = new MyPopUpViewModel();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.