代码之家  ›  专栏  ›  技术社区  ›  lecloneur

将组合框绑定到枚举引发异常

  •  -1
  • lecloneur  · 技术社区  · 7 年前

    没有发现这不起作用的原因:

    我有一个 ComboBox 在一个 UserControl 在哪里 ItemSource 绑定到 Enum 使用 ObjectDataProvider 以下内容:

    xmlns:ViewModels="clr-namespace:CMiX.ViewModels"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    
    <UserControl.Resources>
        <ResourceDictionary>
            <ObjectDataProvider x:Key="Blend" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
                <ObjectDataProvider.MethodParameters>
                    <x:Type TypeName="ViewModels:BlendMode"/>
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </ResourceDictionary>
    </UserControl.Resources>
    
    
    <ComboBox
        SelectedItem="{Binding BlendMode}"
        ItemsSource="{Binding Source={StaticResource Blend}}">
    </ComboBox>
    

    枚举相当简单:

    namespace CMiX.ViewModels
    {
        public enum BlendMode
        {
            Normal,
            Add,
            Subtract
        };
    }
    

    最后是 SelectedItem 绑定到 ViewModel 带着财产的 BlendMode 以下内容:

    private BlendMode _blendMode;
    public BlendMode BlendMode
    {
        get => _blendMode;
        set => SetAndNotify(ref _blendMode, value);
    }
    

    现在,如果我想运行应用程序,我得到了:

    System.NullReferenceException: 'Object reference not set to an instance of an object.'
    
    Set property 'System.Windows.ResourceDictionary.Source' threw an exception.'
    

    不幸的是,我真的不知道为什么。

    1 回复  |  直到 7 年前
        1
  •  0
  •   lecloneur    7 年前

    这个 MethodName 应该是 GetNames 而不是 GetValues 然后它就开始工作了。