Search code examples
wpfxaml

Bind code behind property to datacontext in WPF XAML


I have a method in my code behind that gets called from which needs to obtain values to make changes to a DataGrid.

I have created a DependencyProperty dictionary in my code behind to store/retrieve the values from:

public Dictionary<string, string> ColumnFormatType
{
  get { return (Dictionary<string, string>)GetValue(ColumnFormatTypeProperty); }
  set { SetValue(ColumnFormatTypeProperty, value); }
}

public static readonly DependencyProperty ColumnFormatTypeProperty
  = DependencyProperty.Register("ColumnFormatType", typeof(Dictionary<string, string>), typeof(UserControlDataGrid), new PropertyMetadata(false));

When I try to add the property to my XAML to bind it to the ViewModel I get a "the property ColumnFormatTypeProperty was not found in type UserControl" error.

<UserControl x:Class="UserControlDataGrid" ColumnFormatTypeProperty="{Binding ColumnFormatTypes}" />

Where/How do I bind the ColumnFormatTypes property to my ViewModel so I can use the values in my codebehind? Perhaps there is a way to bind it from the codebehind?

Or should I make the viewmodel/s that I use for the control implement an interface and access the property direct via the DataContext (which seems to be against the MVVM principles)?

p.s. I have searched extensively but every answer I find talks about binding the property to a property on a control rather than to the property in the code behind of the UserControlDataGrid.

pps. I found this code to bind from the code behind:

SetBinding(ColumnFormatTypeProperty, "ColumnFormatTypes");

but I'm getting an error: Default value type does not match type of property 'ColumnFormatType'.

Here's the property on my ViewModel:

public Dictionary<string, string> ColumnFormatTypes { get { return _columnFormatType; } set { _columnFormatType = value; NotifyPropertyChanged(); } }
        Dictionary<string, string> _columnFormatType = new Dictionary<string, string>();

Solution

  • Ok, seems I was able to figure it out.

    Define the property and dependency property in the code behind:

    public Dictionary<string, string> ColumnFormatType
    {
        get { return (Dictionary<string, string>)GetValue(ColumnFormatTypeProperty); }
        set { SetValue(ColumnFormatTypeProperty, value); }
    }
    
    public static readonly DependencyProperty ColumnFormatTypeProperty
     = DependencyProperty.Register("ColumnFormatType", typeof(Dictionary<string, string>), typeof(UserControlDataGrid), new PropertyMetadata(default(Dictionary<string, string>)));
    

    Then set the binding in the contructor of the class:

    public UserControlDataGrid()
    {
        InitializeComponent();
        SetBinding(ColumnFormatTypeProperty, "ColumnFormatTypes");
    }