选择项时,UWP XAML ComboBox会抛出StackOverflowException

时间:2017-11-10 17:39:10

标签: xaml combobox uwp

当在UI中更改选择时,我的XAML ComboBox控件陷入无限循环。 ComboBox设置绑定属性的值。当属性发生更改时,会引发属性更改事件。这反过来又导致数据仓再次更新属性。这会一直循环,直到我收到堆栈溢出异常。

                   <ComboBox x:Name="OriginCountryCode"  Grid.ColumnSpan="2" Grid.Column="2" SelectedValue="{x:Bind Mode=TwoWay, Path=ViewModel.OriginCountryCode}"  DisplayMemberPath="Value" SelectedValuePath="Key" ItemsSource="{x:Bind ViewModel.CountryCodes}"   />

控件绑定到以下属性。

    private static  Dictionary<string, string> _countryCodes = null;
    public Dictionary<string, string> CountryCodes
    {
        get
        {
            if (_countryCodes != null) return _countryCodes;

            _countryCodes = new Dictionary<string, string>();
            var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            foreach (var culture in cultures)
            {
                var region = new RegionInfo(culture.LCID);
                _countryCodes[region.TwoLetterISORegionName] = region.DisplayName;
            }
            return _countryCodes;
        }
    }

    public string OriginCountryCode
    {
        get => _origin.CountryCode;
        set
        {
            _origin.CountryCode = value; RaisePropertyChanged(nameof(OriginCountryCode));
        }
    }

此行为很奇怪,因为我的所有其他控件都没有出现此行为。 BAML为ComboBox生成的连接器代码是不同的。一个是焦点更改时更新,另一个是SelectedValue更改时更新。

            case 15: // Views\QuotesPage.xaml line 77
                this.obj15 = (global::Windows.UI.Xaml.Controls.TextBox)target;
                (this.obj15).LostFocus += (global::System.Object sender, global::Windows.UI.Xaml.RoutedEventArgs e) =>
                {
                    if (this.initialized)
                    {
                        // Update Two Way binding
                        this.dataRoot.ViewModel.DestinationPostalCode = this.obj15.Text;
                    }
                };
                break;
            case 16: // Views\QuotesPage.xaml line 78
                this.obj16 = (global::Windows.UI.Xaml.Controls.ComboBox)target;
                (this.obj16).RegisterPropertyChangedCallback(global::Windows.UI.Xaml.Controls.Primitives.Selector.SelectedValueProperty,
                    (global::Windows.UI.Xaml.DependencyObject sender, global::Windows.UI.Xaml.DependencyProperty prop) =>
                    {
                    if (this.initialized)
                    {
                        // Update Two Way binding
                        this.dataRoot.ViewModel.DestinationCountryCode = (global::System.String)this.obj16.SelectedValue;
                    }
                });
                break;

1 个答案:

答案 0 :(得分:2)

当属性值未更改时,不要引发PropertyChanged

public string OriginCountryCode
{
    get => _origin.CountryCode;
    set
    {
        if (_origin.CountryCode != value)
        {
            _origin.CountryCode = value; 
            RaisePropertyChanged(nameof(OriginCountryCode));
        }
    }
}