locked
binding usercontrol property RRS feed

  • Question

  • Hi

    I have a property in my usercontrol:

        public partial class Bill : UserControl
        {
            public int Id { get; set; }

            void SetBinding()
            {
                this.SetBinding(this, new Binding("Id"));
            }

            public Bill()
            {
                InitializeComponent();
                SetBinding();
            }
        }

    ...and I want know how to bind it

    Monday, April 6, 2009 7:58 AM

Answers

  •  The binding doesn't work as your wrote it.

    The SetBinding method requires :

    - a target, which is a dependency property, like UserControl.WidthProperty. What is your expected target ?

    - and a binding object, ok for your example.

    ==> SetBinding( UserControl.WidthProperty, new Binding("Id"));

    Then the binding requires a data source. Two possibilities :

    1) provide a DataContext to one of parent XAML object, your UserControl for example (but it can a Grid...), so you have to write : this.DataContext = Id;

    2) or provide the source in your binding object, when you call the SetBinding method.

    With these hints, it should work...

    But only in the default mode : OneWay, not TwoWay. OneWay is : a change on the source affects the target. TwoWay is : a change on the source affects the target and vice-versa.

    For using the TwoWay mode, you have to create a class which implements the INotifyPropertyChanged interface. See the official tutorial for explanations :

    http://silverlight.net/learn/tutorials/databinding.aspx

    Monday, April 6, 2009 9:08 AM