加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在不触发SelectionChanged事件的情况下设置Combobox的选定

发布时间:2020-12-16 00:10:39 所属栏目:百科 来源:网络整理
导读:我有一个ComboBox: ComboBox Name="drpRoute" SelectionChanged="drpRoute_SelectionChanged" / 我在代码隐藏文件中设置列表项: public ClientReports(){ InitializeComponent(); drpRoute.AddSelect(...listofcomboxitemshere....)}public static class C
我有一个ComboBox:

<ComboBox Name="drpRoute" SelectionChanged="drpRoute_SelectionChanged" />

我在代码隐藏文件中设置列表项:

public ClientReports()
{
    InitializeComponent();
    drpRoute.AddSelect(...listofcomboxitemshere....)
}


public static class ControlHelpers
{
    public static ComboBox AddSelect(this ComboBox comboBox,IList<ComboBoxItem> source)
    {
        source.Insert(0,new ComboBoxItem { Content = " - select - "});

        comboBox.ItemsSource = source;
        comboBox.SelectedIndex = 0;

        return comboBox;
    }
}

出于某种原因,当我设置SelectedIndex时,SelectionChanged事件被触发了.

我如何设置ItemSource并设置SelectedIndex而不触发SelectionChanged事件?

我是WPF的新手,但肯定不应该像看起来那么复杂吗?或者我在这里遗失了什么?

解决方法

您可以使用数据绑定解决此问题:

private int _sourceIndex;
public int SourceIndex
{
    get { return _sourceIndex; }
    set
    {
        _sourceIndex= value;
        NotifyPropertyChanged("SourceIndex");
    }
}

private List<ComboBoxItem> _sourceList;
public List<ComboBoxItem> SourceList
{
    get { return _sourceList; }
    set
    {
        _sourceList= value;
        NotifyPropertyChanged("SourceList");
    }
}

public ClientReports()
{
    InitializeComponent();

    // Set the DataContext
    DataContext = this;

    // set the sourceIndex to 0
    SourceIndex = 0;

    // SourceList initialization
    source = ... // get your comboboxitem list
    source.Insert(0,new ComboBoxItem { Content = " - select - "});
    SourceList = source
}

在XAML中绑定SelectedItem和ItemsSource

<ComboBox Name="drpRoute" 
   ItemsSource="{Binding SourceList}"
   SelectedIndex="{Binding SourceIndex}" />

使用数据绑定,每次在代码中更改SourceIndex时,它都会在UI中更改,如果您在UI中更改它也会在类中更改,您可以尝试查找有关MVVM设计模式的教程,这是编写WPF应用程序的好方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读