Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my WPF Command not firing?

Tags:

c#

mvvm

wpf

I have this XAML:

<UserControl x:Class="Foo.UserControls.Bar"
             x:Name="FooBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel>
        <WrapPanel Margin="4,0,0,0">
            <Button Command="{Binding Path=CreateCommand, ElementName=FooBar}">
                <TextBlock>Create</TextBlock>
            </Button>

with this code-behind (removed usings):

namespace Foo.UserControls
{
    public partial class Bar : UserControl
    {
        public DelegateCommand CreateCommand { get; private set; }

        public Bar()
        {
            InitializeComponent();

            CreateCommand = new DelegateCommand(Create);
        }

        private void Create(object action)
        {
            Console.WriteLine("foo");
        }
    }
}

Both with debugger and console logging, it doesn't seem to ever fire. The odd thing is that the binding seems to be just fine, because it does not log any errors to the output. If I purposely break the binding I do get a binding error, but with the above binding I do not get any errors yet it never fires.

like image 742
Tower Avatar asked Jan 17 '23 13:01

Tower


1 Answers

Try putting CreateCommand = new DelegateCommand(Create); before InitializeComponent();

like image 141
Euphoric Avatar answered Jan 20 '23 14:01

Euphoric