簡體   English   中英

設置Combobox的選定值而不觸發SelectionChanged事件

[英]Setting a Combobox 's selected value without firing SelectionChanged event

我有一個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;
    }
}

出於某種原因,當我設置SelectedIndexSelectionChanged事件被觸發了。

我如何設置ItemSource並設置SelectedIndex而不觸發SelectionChanged事件?

我是WPF的新手,但肯定不應該像看起來那么復雜嗎? 或者我在這里遺失了什么?

無論是通過代碼還是通過用戶交互設置, SelectionChanged事件都將觸發。 要解決這個問題,您需要在代碼中更改處理程序,如@Viv建議的那樣,或者在代碼中更改代碼時添加一個標志來忽略更改。 第一個選項不會觸發事件,因為您沒有收聽它,而在第二個選項中,您需要檢查標志以查看它是否是由代碼更改觸發的。

更新:這是使用標志的示例:

bool codeTriggered = false;

// Where ever you set your selectedindex to 0
codeTriggered = true;
comboBox.SelectedIndex = 0;
codeTriggered = false;

// In your SelectionChanged event handler
if (!codeTriggered)
{
   // Do stuff when user initiated the selection changed
}

您可以使用數據綁定解決此問題:

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應用程序的好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM