开发者

How to avoid rising ComboBox SelectionChanged event when doing it in codebehind in WPF?

I have a function that will change a combo box selected index, so combobox_selectionchanged event will rise automatically,but the handler of this event call my function again,so the function will be called twice!!

IS there any way to prevent rising selection_changed event in function below?

private void Refresh_Window()
{
    Monthes_ComboBox.SelectedIndex = DM.Month - 1;
}

I wanted to avoid a long description about my problem, so I just asked the question. I'm designing a calendar, the combo_box contains monthes of a year, but there are two buttons that will go to nextmonth or previous month,so I have to change the combo_box index by code, I create a function and I called it in f开发者_如何学Corm_load and combobox_Selection_changed and button_click Can I design it in a better way? and Refresh_window doesn't just change the combobox_selectedindex, it changes all Labels and TextBlocks in form, so I just wanted all changes to be done by Refresh_window


private bool _refreshCalled = false;

private void Refresh_Window()
{
    _refreshCalled = true;
    try
    {
        ....
        Monthes_ComboBox.SelectedIndex = DM.Month - 1;
        ....
    }
    finally
    {
        _refreshCalled = false;
    }
}

private void OnComboBoxSelectedChanged(object sender, EventArgs e)
{
     ...
     if (!_refreshCalled)
     {
         Refresh_Window();
     }
     ...
}


if you use a function to raise an event and you call that same function from the event handler, to what I understand this is at minimum badly designer and not optimal.

in general with combo boxes you can simply assign the SelectedValue and the control will select the item with that value then the selected index will change to the index of such item, you would not really need to set the selected index directly...

if you really want to work by index anyway you are free to do but I would avoid this spaghetti coding having a method which change the selected index if the same method is also called by the event handler attached to the event fired...


There are a couple of good ways to do this:

  • Set a variable that indicates the selected index is changing in the combobox (you'll need to derive from the built-in ComboBox class). If selected index changes again from deeper in the call stack, the variable will still be set and you can read it before trying to change the selected index again.

  • Similarly, if the call stack involves handlers attached to the combobox, you can override OnSelectedIndexChanged and not perform any logic if this is the second time the selected index has changed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜