Search code examples
wpfbindingbehind

How can I bind static variable in wpf code behind?


I have static class 'MappingService'.

public  class MappingService : INotifyPropertyChanged
{
    static readonly MappingService _Instance = new MappingService();
    public static MappingService Instance
    {
        get { return _Instance; }
    }

    public Efficiency Source { get; set; }
}

and create ComboBox in code behind.
I want to bind ItemsSource MappingService.Instance.Source in code behind.

comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("MappingService.Instance.Source") { Mode = BindingMode.TwoWay });

but I can't access MappingService.Instance.Source.

Pleas help me. thank you.


Solution

  • Here how you can bind:

    var propertyPath = new PropertyPath("Source");
    var binding = new System.Windows.Data.Binding
    {
         Path = propertyPath,
         Mode = BindingMode.TwoWay,
         Source = MappingService.Instance
    };
    BindingOperations.SetBinding(
        comboBox,
        System.Windows.Controls.ItemsControl.ItemsSourceProperty,
        binding);