0

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 Answers2

1

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.

Kumar
  • 182
  • 13
  • I can't understand point. combobox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("MappingService.Instance.Source") { Mode = BindingMode.TwoWay }); It is not work. – user3214694 Mar 30 '16 at 06:06
1

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);
Clemens
  • 123,504
  • 12
  • 155
  • 268
Nitin
  • 18,344
  • 2
  • 36
  • 53