等待某种情况后 再绑定事件

功能:

     有两个combobox,当改变第一个combobox时,第二个combobox会重新绑定新的数据源, 当第二个改变时,第一个也会重新绑定新的数据源

遇到的问题:

    当改变第一个combobox时,第二个combobox会触发事件改变了数据源,但随之第二个combobox也改变了,又触发了第一个combobox事件

解决方法之一:

    先解绑,后用Dispatcher.BeginInvoke()的方式绑定

private void FromBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
     this.ToBox.SelectionChanged -= this.ToBox_SelectionChanged_1;
     if (((Selector)e.Source).SelectedValue == null) return;
     string name = ((Selector)e.Source).SelectedValue.ToString();

     DataTable dt = CarAreaSubManager.Create().SelectTagSource(name);
     DataView dv = dt.DefaultView;
     this.ToBox.ItemsSource = dv;
     this.ToBox.DisplayMemberPath = "area_sub_name";
     this.ToBox.SelectedValuePath = "area_sub_name";
     this.Dispatcher.BeginInvoke(new Action(() => { this.ToBox.SelectionChanged += this.ToBox_SelectionChanged_1; }), DispatcherPriority.ApplicationIdle);

}

private void ToBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
     this.FromBox.SelectionChanged -= this.FromBox_SelectionChanged_1;

     if (((Selector)e.Source).SelectedValue == null) return;
     string name = ((Selector)e.Source).SelectedValue.ToString();

     DataTable dt = CarAreaSubManager.Create().SelectFromSource(name);
     DataView dv = dt.DefaultView;
     this.FromBox.ItemsSource = dv;
     this.FromBox.DisplayMemberPath = "area_sub_name";
     this.FromBox.SelectedValuePath = "area_sub_name";

     this.Dispatcher.BeginInvoke(new Action(() => { this.FromBox.SelectionChanged += this.FromBox_SelectionChanged_1; }),DispatcherPriority.ApplicationIdle);
}

原文地址:https://www.cnblogs.com/ykgbk/p/10749625.html