2014-10-30 74 views
0

我在代碼背後有一個屬性文件。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變爲空常會導致不更新組合框?應該是什麼解決方案?

+0

停止設置'propertyName' = NULL? – 2014-10-30 17:22:39

+1

您是否在任何時候設置了DataContext? – furkle 2014-10-30 17:23:23

+0

嘗試刪除組合框selectedvalue上的相對源 – DLeh 2014-10-30 17:28:34

回答

0

我相信你是有約束力的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}}" 
相關問題