开发者

How to change the Combobox.Text property when Combobox is bound to data?

My scenerio is like this:

At runtime, I bind ToolStripComboBox to array of struct:

cbxTimes.ComboBox.DataSource = PlayTimeLengths;
cbxTimes.ComboBox.DisplayMember = "Description";
cbxTimes.ComboBox.ValueMember = "Minutes";

The DropDownStyle of ToolStripCombobox is set to DropDown.

Everything is working fine, I can select values from the dropdown list and I can write text in the control.

However I wanted to prevent user from pressing some controls and alternate the Text property when some other controls are pressed.

I am trying to accomplish this in KeyPress event:

private void cbxTimes_KeyPress(object sender, KeyPressEventArgs e)
{
    var cbxSender = ((ToolStripComboBox)sender).ComboBox;
    string S = cbxSender.Text;
    //some operations on the S variable
    cbxSender.Text = S;
    e.Handled = true;
} // breakpoint here shows that cbxSender.Text is not changed to S!

So the Text propert开发者_如何学运维y has not been changed but I didn't get any exception. However, if I run the program further (I quit from the debugging) I see that the Text property is changed - to be more specific. I see the text from S inside the control.

Now, imagine that I press any key for the second time, and again I am in the debugger in the same event:

private void cbxTimes_KeyPress(object sender, KeyPressEventArgs e)
{
    var cbxSender = ((ToolStripComboBox)sender).ComboBox;
    string S = cbxSender.Text; // this time breakpoint is here
    //some operations on the S variable
    cbxSender.Text = S;
    e.Handled = true;
} // breakpoint here shows that cbxSender.Text is not changed to S!

But this time I put breakpoint on the second line and after examining the Text property I see that it still has not changed. Despite the fact that I've altered it on the first time when the event was fired up and the altereted text is visible in the control. But under debugger I see different value, I see value that has been set up at the begining. Value which belongs to the array of structs.

SO what can I do to overcome this problem?


Honestly this is one of the things I hate about Windows Forms databinding. In WPF you would not bind to the objects directly, you'd bind to a "ViewModel" object which encapsulated this view logic you have and bind to it instead.

My workaround to all of this would be to just not use databinding for this case at all and manually populate the items as needed. I can understand why you might be having this problem. If you had updated your underlying bound object's .Text (or whatever causes ToString() to display the value), you would probably see the new value you'd set, but that upsets the semantics of your underlying objects, which is Not A Good Thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜