0

I have the following ViewModel:

public class ViewModel : INotifyPropertyChanged {
    public ObservableCollection<A> MyCollection { get; set; }
    public RelayCommand Command1{ get; set; }

    public ViewModel() {
        Command1= new RelayCommand(Method1);
    }

    void Method1() {
        ...
    }
}

And this View:

<UserControl x:Class="TemplateEditor.Views.View"
xmlns:vm="clr-namespace:TemplateEditor.ViewModels"
DataContext="{DynamicResource ViewModel}">

    <UserControl.Resources>
        <vm:ViewModel x:Key="ViewModel"/>
    </UserControl.Resources>

    ...

    <Button DataContext="{StaticResource FormIdBlockViewModel}"  Content="qwe" Command="{Binding Command1}" />

    ...
</UserControl>

The button works fine in this case, but I want to move all commands into a certain file. So, if I create AppCommands.cs file:

public class AppCommands
{
    private static RelayCommand Command1 { get; set; }

    static AppCommands()
    {
        Command1 = new RelayCommand(Method1);
    }

    public static void Method1(object parameter)
    {
        ....
    }
}

Also, I change View:

...
xmlns:commands="clr-namespace:TemplateEditor.Common"
...
<UserControl.Resources>
    <vm:ViewModel x:Key="ViewModel"/>
    <commands:AppCommands x:Key="AppCommands"/>

...

<Button DataContext="{StaticResource AppCommands}" Content="qwe" Command="{Binding Command1}"  />

The command does not work.

Could you please to advise how to perform binding to AppCommands.Commands?

ztsv
  • 880
  • 2
  • 12
  • 27
  • Acc to me, you should get compile time error at "public static void Method1(object parameter)" , didn't you get it? – Nikita Shrivastava Oct 07 '15 at 02:36
  • No, I do not get any errors. – ztsv Oct 07 '15 at 02:37
  • RelayCOmmand would not allow you to have method with parameter, since it expects an Action() – Nikita Shrivastava Oct 07 '15 at 02:37
  • 1
    Why is your Command private? Did you try [this](http://stackoverflow.com/questions/3862455/binding-to-static-class-property)? – Daniel Castro Oct 07 '15 at 02:37
  • Rest of the things works fine for me with Command={Binding Command1,Source={StaticResource AppCommands}}. – Nikita Shrivastava Oct 07 '15 at 02:40
  • 2
    `Command1` is a private static property. You cannot bind to it by pulling from an instance of `AppCommands`. You can just set the `Command` to the static property (requiring public) like this `Command="{x:Static commands:AppCommands.Command1}"` – Hopeless Oct 07 '15 at 02:41
  • @DanielCastro OMG! It is my big mistake that Command1 is private. I just did it public and it works fine! Thank you! – ztsv Oct 07 '15 at 02:45

0 Answers0