【问题标题】:WPF PropertyChanged is nullWPF PropertyChanged 为空
【发布时间】:2014-10-30 17:18:08
【问题描述】:

我在代码隐藏文件中有一个属性。

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 经常导致不更新组合框?应该怎么解决?

【问题讨论】:

  • 停止设置propertyName = null?
  • 你有没有在任何时候设置过DataContext?
  • 尝试删除组合框 selectedvalue 上的相对源

标签: wpf propertychanged


【解决方案1】:

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

SelectedValue="{Binding DataContext.SelectedTypeID, 
     RelativeSource={RelativeSource AncestorType={x:Type local:EditConditionListLayer}}}"

我也怀疑你的ComboBox 本身是否有你想要的DataContext,如果是这样的话:

SelectedValue="{Binding DataContext.SelectedTypeID, 
                        RelativeSource={RelativeSource Self}}" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2011-04-05
    • 2018-11-19
    • 2014-06-15
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    相关资源
    最近更新 更多