Search code examples
c#mvvmwinrt-xaml

How to bind a DependencyProperty in a UserControl to a DataContext property? Windows Store


I have a UserControl with a Dependency Property:

 public static readonly DependencyProperty Step2CommandProperty =
        DependencyProperty.Register("Step2Command", typeof(ICommand), typeof(MyTripNavigationStep), new PropertyMetadata(null));

    public ICommand Step3Command
    {
        get { return (ICommand)GetValue(Step3CommandProperty); }
        set { SetValue(Step3CommandProperty, value); }
    }

Then I have a ViewModel with a ICommand property:

  public ICommand SaveStep1Command
    {
        get
        {
            return new RelayCommand(() =>
            {


            });

        }
    }

Then I Bind the two properties like this in the Page where i have the viewModel as the DataContext and the UserControl.

            <UserControls:Step Step3Command="{Binding SaveStep1Command, Mode=OneWay}" />

The binding is not being applied, and the Step3Command in the userControl always appears to be null. I know that the DataContext is working fine, and that Visual Studio does not allow me to put TwoWay binding. I'm using GalaSoft Simple Mvvm and Visual Studio CTP update 2.

Anybody has a clue of what am I doing wrong? thanks.


Solution

  • You defined the property wrong. The get block gets called everytime the property is accessed, so everytime you (or the MVVM magic in WPF) accesses SaveStep1Command a new command is created. This is not what you want.

    Rewrite the property like this:

    In your constructor code, write:

    SaveStep1Command = new RelayCommand(...)
    

    And define your property just like this:

    public ICommand SaveStep1Command { get; }
    

    If you are on an older version of .net / C#, you must define it like this:

    public ICommand SaveStep1Command { get; private set; }
    

    Explanation attempt: It might be that the databinding only creates weak references. With your way of defining the SaveStep1Command it is created once the binding is set up, and then it just "lies around" on the heap - and when the GC kicks in next time, the space is freed up because it has no strong references.