开发者

Winform Custom Control: Why Setter not called when used from Constructor?

I have an initial value property like this:

    [Category("Main")]
    [Description("Intial Value")]
    [DefaultValue(10)]
    public int InitialValue
    {
        get { return m_initialValue; }
        set { 
            m_initialValue = value;
            this.TrackBar.Value = this.m_initialValue;
        }
    }

So in my constructor I do this for example:

        this.I开发者_开发技巧nitialValue = 10;

To my surprise when dragging the custom control on a form the setter is not called so that my trackbar value is not synchronized.

Why ?

Only when I change the property in dialog box the setter is called.


I decided to take your advice as suggested in one of the comments:

You can try by yourself will take 2 minutes.

So I did (it took about 3 minutes), and I was unable to reproduce the behavior that you described.

Here are the exact steps that I followed:

  1. Created a new Windows Forms Application.
  2. Added a new User Control to my project.
  3. Opened the new User Control in design view and added a TrackBar control (leaving the TrackBar control's properties all set to their defaults).
  4. Added the following code to the User Control class (exactly the same as you posted above, with the addition of a private field m_initialValue that you omitted from the original example):

    public class UserControl1 : UserControl
    {
       public UserControl1()
       {
           InitializeComponent();
           this.InitialValue = 10;
       }
    
    
       [Category("Main")]
       [Description("Intial Value")]
       [DefaultValue(10)]
       public int InitialValue
       {
           get { return m_initialValue; }
           set
           {
               m_initialValue = value;
               this.trackBar1.Value = this.m_initialValue;
           }
       }
    
    
       int m_initialValue;
    }
    

  5. Built the project.
  6. Opened the default Form (Form1) that was created with the new project in design view.
  7. Dragged the User Control that I had just created (UserControl1) out of the toolbox where it was automatically placed and onto the surface of the form.

The indicator on the slider bar appeared all the way to the right side (the correct and expected position given the default Maximum value of 10). Now, you tell me: What are we doing differently?


Try adding [Browsable(true)] .


The key portion of your question is here:

when dragging the custom control on a form

You're still in the designer, and the designer cheats a bit to render things. Does this still happen when you actually run the application?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜