FINDarkside
FINDarkside

Reputation: 2445

Binding user control to property

I am trying to make custom control and bind that to static field. I'm kinda stuck but this is how I would want it to work:

<BooleanControl desc="Description" bind = {Binding Save.b}/>

Desc would be the description for the checkBox, Save is class that holds the field b which needs to be binded to the control.

I'm making custom control because I also need to be able to make the control by giving description and reference to the field to constructor.

Here's what I have now:

public partial class BooleanControl : UserControl
{
    public string desc { set; get; }

    public BooleanControl()
    {
        InitializeComponent();
    }
}

But I am not sure if this is the right way to do it, since I am not going to change the description, I just need to set it in designer and by giving the value to constructor. I am still missing the part where I update Save.b according to the value of checkbox (inside BooleanControl) because I'm not sure what is the right way to do it.

Upvotes: 1

Views: 86

Answers (1)

Maxime Tremblay-Savard
Maxime Tremblay-Savard

Reputation: 967

Create a dynamic property of type "yourclass" named Bind and when it is filled do what you want with it. It would look like this:

public YourClass Bind
    {
        get { return (YourClass)GetValue(BindProperty); }
        set { SetValue(BindProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Bind.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BindProperty =
        DependencyProperty.Register("Bind", typeof(YourClass), typeof(UserControl1), new PropertyMetadata(BindModified));

    private static void BindModified(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((UserControl1)d).AttachEventHandler();
    }

    private void AttachEventHandler()
    {
        //Modify what you want here
    }

And you would simply use it as you wanted:

<BooleanControl Bind="{Binding Save.b}"/>

Upvotes: 1

Related Questions