wpf - 将 UpdateSourceTrigger 设置为 LostFocus 时的绑定(bind)异常

标签 wpf mvvm binding behavior updatesourcetrigger

以下代码在 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/

相关文章:

带有格式的 WPF 文本框绑定(bind)

c# - 通过 XAML 调用静态类中的静态方法

c# - 从WPF MVVM应用程序将参数传递给WPF用户控制库

c# - 在 WPF MVVM 应用程序中的选项卡之间正确导航

WPF DataGrid 绑定(bind)、调整单元格内大数据(~75k)大小的速度非常慢

c# - 如何在代码隐藏中将 Unicode 字符设置为标签的内容?

javascript - 代码隐藏文件是否与 View 模型相同?

c - 脚本和主机应用程序之间的责任

c - 尝试打印最佳数组 : "Name lookup of ' k' changed for new ISO 'for"

wpf - 如何提高 RelativeSource FindAncestor 的性能?