Search code examples
c#wpfcommanddatacontextfunction-call

How to call a command from window pop in wpf


How call a delegate command from window pop up. I'm showing a pop up window over a window.. The pop up window have button which need to call DelegateCommand from ViewModel.

Below is the code for Window > MyPopUp.xaml.cs

public partial class MyPopUp : Window
{
  public MyPopUp(){
     InitializeComponent();
    }
}

Below is the code for 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 code here

<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>

Though when InitializeComponent(); is called in MyPopUp.xaml.cs the window DataContext get all the commands in it from MyPopUpViewModel.cs

Then when clicked on button on pop up... It should call the command AddCommand, but it is not getting called.

Let me know what I'm missing or sommnething need to be added/change.

Thanks in advance.


Solution

  • Digging for so much time on wpf and trying some alternative.. i got the answer 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"/>