SamuelWarren
SamuelWarren

Reputation: 1459

RaisePropertyChanged throwing a StackOverflow Exception on TwoWay Bound property

So I've got the following ComboBox with the SelectedValue bound to the Property below. With the following binding, when I set value, the binding/RaisePropertyChanged combination is throwing a StackOverflow Exception.

Here's the ComboBox

<ComboBox x:Name="WireType" ItemsSource="{x:Bind ViewModel.WireTypes}" SelectedValue="{x:Bind ViewModel.WireType, Mode=TwoWay}"/>

Here's the Property

public string WireType
{
    get
    {
        return _wireType;
    }
    set
    {
        _wireType = value;
        RaisePropertyChanged();
    }
}

And here's the RaisePropertyChanged method.

private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(caller));
    }
}

I'm pretty sure I've done this before. What am I missing?

Upvotes: 2

Views: 1032

Answers (2)

theB
theB

Reputation: 6738

My psychic powers suggest that the PropertyChanged event is trying to set the property value.

The setter should protect against the case where the value didn't change. ie-

set
{
    if (_wireType != value) // or the appropriate comparison for your specific case
    {
        _wireType = value;
        RaisePropertyChanged();
    }
}

Of course a stack trace would confirm what's actually happening.

Upvotes: 3

Mohit S
Mohit S

Reputation: 14044

Try this

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
  if (this.PropertyChanged != null)
    this.PropertyChanged(this, new PropertyChangedEventArgs(caller));
}

Upvotes: -1

Related Questions