WPF PropertyChanged为null

时间:2014-10-30 17:18:08

标签: wpf propertychanged

我在代码后面有一个属性。

private int? selectedTypeID = null;
public int? SelectedTypeID
{
  get
  {
    return selectedTypeID;
  }
  set
  {
    selectedTypeID = value;
    OnPropertyChanged( "SelectedTypeID" );
  }
}

这是PropertyChanged的代码。注释行中提到了这个问题,请参阅。

#region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged( string propertyName )
    {
      /*PropertyChanged appears to be null in some cases while in some cases it is not null. I have also tried to explicity assigning it the DataContext but that does not work as well. */
      if( PropertyChanged != null )
        PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
    }

#endregion


//This line is in DataContext file where the problematic property is assigned a null.
editLayerSidebar.editConditionIngredient.SelectedTypeID = null;

//This is the combobox xaml where SelectedTypeID has been bound to SelectedValue.
<ComboBox x:Name="TypeCombo" Grid.Row="3" Grid.Column="1" Margin="5,5,0,0" 
                  ItemsSource="{Binding DataContext.IngredientTypes, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:EditConditionListLayer}}}"
                  DisplayMemberPath="Name" SelectedValuePath="ID" SelectedValue="{Binding SelectedTypeID, RelativeSource={RelativeSource Mode=Self}}" >

为什么ProperyChanged变为null经常导致不更新组合框?应该是什么解决方案?

1 个答案:

答案 0 :(得分:0)

我相信您绑定SelectedValue错误。您的ComboBox本身没有任何名为SelectedTypeID的属性。它应该是您的视图模型的一些属性。在这种情况下,RelativeSource应该沿着可视树向上移动,以定位一些具有您想要的DataContext的源(在这种情况下,我猜它的类型为local:EditConditionListLayer),{{1}然后应该Path作为前缀:

DataContext

另外,我怀疑即使你的SelectedValue="{Binding DataContext.SelectedTypeID, RelativeSource={RelativeSource AncestorType={x:Type local:EditConditionListLayer}}}" 本身也有你想要的ComboBox,如果是的话,也可能是:

DataContext