XAML ComboBox SelectionChanged Fires OnLoad

荒凉一梦 提交于 2020-01-13 08:35:08

问题


If I have a ComboBox that has a SelectionChanged event, it fires when I'm loading the control.

So at page load I set the SelectedValue and the SelectionChanged event fires which is not what I want to happen.

What is the accepted apporach to stopping this?


回答1:


Two obvious solutions to this would be 1) Wait until the Loaded event of the Window/Page/UserControl which contains the ComboBox and hook up SelectionChanged there...eg in the constructor:

// set the inital selected index for the combo box here...

this.Loaded += (s, args) =>
               {
                    cmbBox.SelectionChanged += 
                            new SelectionChangedEventHandler(HandleChanged);
               };

or 2) Check that the ComboBox has loaded in the selection changed handler before doing anything and return if it hasn't...eg in the handler:

if (!cmbBox.IsLoaded)
        return;

I would prefer number 1 as it doesn't require the check every time the SelectionChanged handler is fired.




回答2:


I faced a particular situation :

If you are using a pivot, and prematurely firing control is in PivotItem > 0, you will still have the problem.

In that case, it seems this.Loaded() only refers to PivotItem "0", and changing to other PivotItem in the UI will fire events anyway.

In that case, the solution is (with your example) :

cmbBox.Loaded += (s, args) =>
           {
                cmbBox.SelectionChanged += 
                        new SelectionChangedEventHandler(HandleChanged);
           };


来源:https://stackoverflow.com/questions/2762042/xaml-combobox-selectionchanged-fires-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!