简体   繁体   English

仅当用户在C#wpf中更改组合框的选择时,才如何触发selectionChange事件?

[英]How to trigger a selectionChange event only when users change the selection of a combobox in C# wpf?

I would like to know how to trigger the selectionChange event of a combobox only when the user himself change the selection of the list. 我想知道仅当用户自己更改列表的选择时如何触发组合框的selectionChange事件。 (Avoid other cases) I found a solution here but I have some errors. (避免其他情况)我在这里找到了解决方案,但有一些错误。 Could you help me? 你可以帮帮我吗?

https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted(v=vs.110).aspx

I added System.Windows.Forms in my .cs file and it says there is an ambiguity beetween 'System.Windows.Controls.ComboBox' and 'System.Windows.Forms.ComboBox' with the first line of the code below. 我在.cs文件中添加了System.Windows.Forms,它说“ System.Windows.Controls.ComboBox”和“ System.Windows.Forms.ComboBox”之间存在歧义,下面是代码的第一行。

I dont know how to cast my sender into a comboBox. 我不知道如何将发件人转换为comboBox。

ComboBox senderComboBox = (ComboBox)sender;

        if (senderComboBox.SelectionLength > 0)
        {
            //code here
        }

Thanks for help! 感谢帮助!

You are trying to reference WinForms ComboBox and not WPF ComboBox . 您尝试引用WinForms ComboBox而不是WPF ComboBox You can listen to SelectionChanged event of the control to know when user changes the selection. 您可以侦听控件的SelectionChanged事件,以了解用户何时更改选择。

A sample code from dotnetperls dotnetperls的示例代码

XAML XAML

<ComboBox
    HorizontalAlignment="Left"
    Margin="10,10,0,0"
    VerticalAlignment="Top"
    Width="120"
    Loaded="ComboBox_Loaded"
    SelectionChanged="ComboBox_SelectionChanged"/>

CS File CS文件

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ... Get the ComboBox.
    var comboBox = sender as ComboBox;

    // ... Set SelectedItem as Window Title.
    string value = comboBox.SelectedItem as string;
    this.Title = "Selected: " + value;
}

This sort of approach worked for me - XAML ComboBox SelectionChanged Fires OnLoad 这种方法对我有用-XAML ComboBox SelectionChanged触发OnLoad

Basically only wire-up the ComboBox_SelectionChanged event after the form has loaded - this will get you around the programmatic change that will fire onload. 基本上,只有在表单加载后才连接ComboBox_SelectionChanged事件-这将使您绕过将触发onload的编程更改。 Beyond that I'm not sure. 除此之外,我不确定。 It might be that you need to use a different event, but I haven't looked into this. 可能是您需要使用其他事件,但是我没有对此进行研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM