如果將UpdateSourceTrigger設置爲PropertyChanged,則會運行以下代碼,但在UpdateSourceTrigger設置爲LostFocus時會在初始化時引發異常。將UpdateSourceTrigger設置爲LostFocus時的異常
這個實現有什麼問題,它如何被糾正?
異常
"'ComboBoxSample.ComboBoxBehavior' type must derive from FrameworkElement or FrameworkContentElement."
查看
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<ComboBox ItemsSource="{Binding Path=Apples}"
DisplayMemberPath="Cultivar">
<i:Interaction.Behaviors>
<local:ComboBoxBehavior
SelectedValue="{Binding Path=SelectedId,
Mode=TwoWay,
UpdateSourceTrigger=LostFocus}"/>
</i:Interaction.Behaviors>
</ComboBox>
</Grid>
行爲
public class ComboBoxBehavior : Behavior<ComboBox>
{
public static readonly DependencyProperty SelectedValueProperty
= DependencyProperty.Register("SelectedValue",
typeof(object),
typeof(ComboBoxBehavior),
new FrameworkPropertyMetadata(null, (target, args) => { }));
public object SelectedValue
{
get { return GetValue(SelectedValueProperty); }
set { SetValue(SelectedValueProperty, value); }
}
protected override void OnAttached() { base.OnAttached(); }
protected override void OnDetaching() { base.OnDetaching(); }
}
視圖模型
public class ViewModel
{
public ObservableCollection<Apple> Apples { get; set; }
public int SelectedId { get; set; }
public ViewModel()
{
Apples = new ObservableCollection<Apple>
{
new Apple()
{
Id = 0,
Cultivar = "Alice",
Weight = 0.250
},
new Apple()
{
Id = 1,
Cultivar = "Golden",
Weight = 0.3
},
new Apple()
{
Id = 2,
Cultivar = "Granny Smith",
Weight = 0.275
}
};
}
}
public class Apple
{
public int Id { get; set; }
public string Cultivar { get; set; }
public double Weight { get; set; }
}
我的目標是弄清楚爲什麼在描述的情況下設置一個UpdateSourceTrigger綁定到一個依賴項屬性爲LostFocus會引發異常,同時將觸發器設置爲PropertyChanged可以正常工作。請注意,上面的代碼只是演示了這種行爲。 – Ilya