XAML ComboBox SelectionChanged 触发 OnLoad

发布于 2024-08-31 08:20:30 字数 156 浏览 2 评论 0 原文

如果我有一个具有 SelectionChanged 事件的 ComboBox,它会在我加载控件时触发。

因此,在页面加载时,我设置了 SelectedValue 并触发 SelectionChanged 事件,这不是我想要发生的情况。

阻止这种情况的公认方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夕嗳→ 2024-09-07 08:20:30

对此的两个明显的解决方案是 1) 等待包含 ComboBox 的 Window/Page/UserControl 的 Loaded 事件并在那里挂钩 SelectionChanged...例如在构造函数中:

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

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

或 2) 检查 ComboBox 是否已加载到选择中在执行任何操作之前更改处理程序,如果没有,则返回...例如在处理程序中:

if (!cmbBox.IsLoaded)
        return;

我更喜欢数字 1,因为它不需要每次触发 SelectionChanged 处理程序时进行检查。

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.

忆依然 2024-09-07 08:20:30

我遇到了一种特殊情况:

如果您正在使用枢轴,并且过早触发控制位于 PivotItem > > 中。 0,你仍然会遇到这个问题。

在这种情况下,似乎 this.Loaded() 仅引用 PivotItem“0”,并且更改为 UI 中的其他 PivotItem 无论如何都会触发事件。

在这种情况下,解决方案是(以您的示例为例):

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

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);
           };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文