1

I my project, I want to use a user control which is the combination of a textblock and a textbox. I can create some custom properties for the usercontrol like

  public string Caption
    {
        get
        {
            return this.Block.Text;
        }
        set
        {
            this.Block.Text = value;
        }
    }

    public string Value
    {
        get
        {
            return this.Box.Text;
        }
        set
        {
            this.Box.Text = value;
        }
    }

I also want to set the binding for the textblock in this usercontrol. I know that we have to use a dependency property for that like below:

  public string fieldValue
    {
        get
        {
            return (string)GetValue(fieldValueProperty);
        }
        set
        {
            SetValue(fieldValueProperty, value);
        }
    }          
    public static readonly DependencyProperty fieldValueProperty =
        DependencyProperty.Register("fieldValue", typeof(string), typeof(TextBlox), 
        new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); 

In my actual application:

  <my:TxtBlox HorizontalAlignment="Left" Name="txtBlox1"                      
                 fieldValue="{Binding Path=ProdCode,Mode=TwoWay}"
                 VerticalAlignment="Top" Width="228" />

I am setting the datacontext of the container of this control to a database object.

 oProd = dt.ProdInfoes.First();
        Main.DataContext = oProd;

But I cant get that to work. Any suggestions?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
sony
  • 1,453
  • 3
  • 35
  • 79

1 Answers1

2

You have to create DependencyProperties Caption and Value instead of plain properties - if you want to bind to them. in your usercontrol xaml you have to set the binding to the properties with ElementName binding. see this post

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74