How can I bind static variable in wpf code behind?

571 Views Asked by At

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.

2

There are 2 best solutions below

1
Nitin On BEST ANSWER

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);
1
Kumar On

This is one simple way to do it.There might be better options than this depends on your deisgn. Try this

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

    public MappingService BindingObject 
    {
    get { MappingService._Instance; }
    }
     public Efficiency Source { get; set; }
   }

And your xaml code.

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

You just add your static reference inside your instance reference.