以下代码在 UpdateSourceTrigger 设置为 PropertyChanged 时运行,但在 UpdateSourceTrigger 设置为 LostFocus 时在初始化时引发异常。
这个实现有什么问题,如何纠正?
异常(exception)
"'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; }
}
最佳答案
你的问题是你试图使用你的 <local:ComboBoxBehavior />
好像它是一个 block (一个框架元素)。在 xaml 中,您只能编写从框架元素(如段落、TextBlock 等)继承的 block 。由于我不确定您要达到的目标,因此这几乎是我可以根据您的详细程度给出的最佳答案。
关于wpf - 将 UpdateSourceTrigger 设置为 LostFocus 时的绑定(bind)异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207725/