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:
- Created a new Windows Forms Application.
- Added a new User Control to my project.
- Opened the new User Control in design view and added a
TrackBar
control (leaving theTrackBar
control's properties all set to their defaults). 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; }
- Built the project.
- Opened the default Form (
Form1
) that was created with the new project in design view. - 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?
精彩评论