2

I have set up my own user control which contains two ComboBoxes, each ComboBox item source is bound to a DependencyProperty. The issue I am having is passing a property from the form that uses my user control to the user control.

Below is my user control:

public static readonly DependencyProperty ListOneProperty = DependencyProperty.Register
    ("ListOne", typeof(List<int>), typeof(LinkedComboBox), new PropertyMetadata(new List<int>()));
    public List<int> ListOne
    {
        get { return (List<int>)GetValue(ListOneProperty); }
        set { SetValue(ListOneProperty, value); }
    }


    public static readonly DependencyProperty ListTwoProperty = DependencyProperty.Register
        ("ListTwo", typeof(List<string>), typeof(LinkedComboBox), new PropertyMetadata(new List<string>()));
    public List<string> ListTwo
    {
        get { return (List<string>)GetValue(ListTwoProperty); }
        set { SetValue(ListTwoProperty, value); }
    }


    public LinkedComboBox()
    {

        InitializeComponent();
        FillListOne();
    }

And below is my MainWindow xaml:

        <control:LinkedComboBox x:Name="LinkedBox" ListTwo="{Binding MyList}"/>

And MainWindow.xaml.cs:

    static List<string> _myList = new List<string>{"abc","efg"};
    public List<string> MyList 
    {
        get { return _myList; }
        set { _myList = value; } 
        }
    public MainWindow()
    {

        InitializeComponent();

    }

What do I need to get the User Control to accept a binding from the Main Window?

Declan Carroll
  • 259
  • 3
  • 9
  • you shouldn't do it like that from the mainview, but you neet to use INotifyPropertyChanged http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist – ZSH Jan 13 '13 at 10:54
  • Why shouldn't I do that from the MainView? If the list I have is created in the main form how should I get it to this control? I'm new to WPF in general so any tips would be appreciated. – Declan Carroll Jan 13 '13 at 16:34
  • if you are just starting ,after you get some knowledge you may want to learn a pattern like MVVM(or MVP or MVC) to get a good grasp how things really work and not just put all the data in the main view and bind it , google mvvm and you can get lots of exampls – ZSH Jan 14 '13 at 07:21

1 Answers1

2

Everything is fine except that you need a PropertyChangedCallback to handle your property.

Here is a simple example

 public static readonly DependencyProperty ListTwoProperty = DependencyProperty.Register
    ("ListTwo", typeof(List<string>), typeof(LinkedComboBox), new PropertyMetadata(new List<string>(), new PropertyChangedCallback(Changed)));

 private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) 
 {  
   //e.NewValue here is your MyList in MainWindow.
 }
Colin
  • 551
  • 2
  • 10