我有一個UserControl,它具有一個ComboBox並綁定到它自己的某個依賴項屬性。ComboBox SelectedItem綁定將NULL寫入源屬性
<UserControl x:Class="XamlParserComboBoxTest.ItemEditor" x:Name="aEditor">
<Grid>
<ComboBox Grid.Row="1"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=Colors}"
SelectedItem="{Binding ElementName=aEditor,
Path=Item.Color,
Mode=TwoWay}"/>
</Grid>
</UserControl>
這DependencyProperty的充滿Item
類型的實例:
public class Item : ViewModelBase
{
private Color _color { get; set; }
public Color Color
{
get { return _color; }
set
{
_color = value;
if (value == null)
{
Console.WriteLine("Color set to NULL");
}
Console.WriteLine(value);
OnPropertyChanged("Color");
}
}
}
public class Color
{
public string Name { get; set; }
}
當用戶控件被替換爲另一個用戶控件,該項目的Color
setter方法被調用NULL
值。綁定到其他控件的屬性不會有任何變化。
雖然我已經解決了這個問題,但我真的需要了解是什麼原因造成的,以及解決問題的最佳方法。
編輯:根據堆棧跟蹤,空值來自Item's
基類,但我不知道如何。完整的源代碼可用here。要重現該問題,請啓動它並按兩次「顯示項目」按鈕。
你的意思是什麼,當UserControl被替換爲另一個UserControl? 「ItemsSource」來自哪裏? –
@HighCore,請檢查源代碼。我只在窗口中心顯示一個編輯器控件,將ContentControl的內容綁定到由我的ICommand實現設置的屬性。 –