以下代码在 UpdateSourceTrigger 设置为 PropertyChanged 时运行,但在 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; }
}