8

你能帮我找出这个错误吗:事件甚至在加载 Windows 窗体之前就触发了。我开始看到消息框,然后单击确定,然后它加载主屏幕。之后一切正常,我想知道是什么在加载窗口之前触发了 ComboBox SelectionChanged 事件。FillComboBoxFamilyData(SegmentCode) 只是创建了一个数据集并将值放入他的 ComboBox。请参阅此链接以获取完整代码。

无法使级联组合框工作

任何帮助将不胜感激。谢谢。

 <ComboBox Height="23" HorizontalAlignment="Left" Margin="35,26,0,0" Name="comboBox1" VerticalAlignment="Top" Width="205" ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}"  DisplayMemberPath="Segment Name" SelectedValuePath="Segment Code" SelectionChanged="comboBox1_SelectionChanged"/>
 <ComboBox Margin="304,26,395,93" Name="comboBox2" />


    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        MessageBox.Show(comboBox1.SelectedValue.ToString());
        SegmentCode = Convert.ToInt32(comboBox1.SelectedValue.ToString());
        FillComboBoxFamilyData(SegmentCode);

    }
4

4 回答 4

16

在将加载数据(由绑定附加)的那一刻,将触发 SelectionChanged。因此,如果您的应用程序已准备好并且所有数据都已加载并附加,您必须检查您的事件处理程序。如果不是,则返回事件处理程序而不做任何事情。此行为是设计使然。

ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}"  

您可以使用IsLoaded-property 来检测绑定是否已被评估。IsLoaded除非数据绑定引擎已评估您的 xaml 绑定,否则不会为真。

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)     { 
   if(!IsLoaded){
      return;
   }
   .... your code here
于 2011-02-16T21:28:19.233 回答
4

您可以使用组合框的 IsLoaded 属性来测试它是否已加载。这是我能找到的最干净、最简单的解决方案:

var comboBox = (ComboBox)sender;
if (!comboBox.IsLoaded)
{
    // This is when the combo box is not loaded yet and the event is called.
    return;
}
于 2016-10-12T22:28:55.720 回答
2

我知道这是一个老问题,但我两次遇到它试图在我的项目中解决这个问题,并得到与 OP 相同的结果。在 IsLoaded 为 true 后填充我的列表。所以,我想我会把我想出来的东西发给别人。只需使用 DropDowOpened 事件将 bool 设置为 true。这样,在用户实际单击下拉列表之前,SelectionChanged 事件不会触发。

private bool UserSeriesChange;
private void comboBox1_DropDownOpened(object sender, EventArgs e)
{
        UserSeriesChange = true;    
}

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ 
   if(!UserSeriesChange){
      return;
   }
   .... your code here
于 2016-05-22T22:55:40.043 回答
0

我遇到了同样的问题,我发现使用 xaml 设置组合框的起始选择索引将在程序加载时触发 selectionchanged 事件,这会导致错误。

要解决此问题,您可以将 selection-index 设置为 -1(默认值)在程序加载后使用代码更改组合框的 current-selection-index。

于 2013-06-13T05:20:29.430 回答