Liran
Liran

Reputation: 830

Invoke Command Within Custom User Control

I'm new to WPF and i'm trying to learn the famous MVVM pattern, I'm facing a small issue (i'm sure) when i try to bind simple command to some ViewModel

this is Simple UserControl i've created:

<UserControl x:Class="MVVM_UsingUserControl_Sample.View.MyUserControl"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             > 
         <StackPanel  DataContext="MyUserControlViewModel" Orientation="Vertical" >

        <Button Margin="0,100,0,0" Height="50" Width="50" Content="PressMe"  Command="{Binding Path=MyCommand}"/>

    </StackPanel>

</UserControl>

and this is the User Control ViewModel

class MyUserControlViewModel : ViewModelBase 
{
        CommandBase m_MyCommand = null;


        public MyUserControlViewModel()
        {

        }

        public ICommand MyCommand
        {
            get
            {
                if (m_MyCommand == null)
                {
                    m_MyCommand = new CommandBase(new Action<object>(DoSomething),
                                                  new Predicate<object>(CanDoSomething));
                }

                return m_MyCommand;
            }
        }

        public void DoSomething(object i_Params)
        {
            MessageBox.Show("Inside MyUserControl DoSomething"); 
        }

        public bool CanDoSomething(object i_Params)
        {
            return true;
        }
}

this is the Main window xaml (no code behaind)

Now the problem is : My main window contains the userControl as is (inside stack panel) and nothing else. i expect the command "MyCommad" will get invoke when i press the button "MyButton" but it doesn't.

anyone has idea why ??? Big thanks.

Upvotes: 0

Views: 953

Answers (1)

ChrisNel52
ChrisNel52

Reputation: 15133

In the constructor of your main window, set its DataContext to your ViewModel.

For example,

this.DataContext = new MyViewModel();

In your XAML, remove

DataContext="MyUserControlViewModel"

since the DataContext will inherit from the main window.

Everything should then work as you expect.

Upvotes: 2

Related Questions