无法将枚举绑定到WPF MVVM中的组合框

5

我阅读了许多关于将枚举绑定到组合框的方法。所以现在在 .Net 4.5 中应该非常容易。但是我的代码不起作用。不太明白为什么。

xaml:

<Window x:Class="SmartTrader.Windows.SyncOfflineDataWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SyncOfflineDataWindow" Height="300" Width="300">
<Grid>
    <StackPanel>
        <ComboBox ItemsSource="{Binding StrategyTypes}" SelectedItem="{Binding StrategyType}" />
        <Button Width="150" Margin="5" Padding="5" Click="Button_Click">Save</Button>
    </StackPanel>
</Grid>

xaml.cs后端

namespace SmartTrader.Windows
{
    /// <summary>
    /// Interaction logic for SyncOfflineDataWindow.xaml
    /// </summary>
    public partial class SyncOfflineDataWindow : Window
    {
        public SyncOfflineDataWindow(IPosition position, ContractType type)
        {
            DataContext = new ObservablePosition(position);
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

视图模型:

namespace SmartTrader.Entity
{
    public class ObservablePosition : NotifyPropertyChanged, IPosition
    {
        public IEnumerable<StrategyType> StrategyTypes =
            Enum.GetValues(typeof (StrategyType)).Cast<StrategyType>();

        public ObservablePosition(IPosition position)
        {
           Strategy = position.Strategy;
        }


        private StrategyType _strategyType = StrategyType.None;
        public StrategyType Strategy
        {
            get { return _strategyType; }
            set
            {
                _strategyType = value;
                OnPropertyChanged();
            }
        }
    }
}

StrategyType是一个枚举类型。但我得到的只是一个空的下拉列表empty combox


1
{Binding StrategyType} - 应该是 {Binding Strategy} 吗? - Jaanus Varus
他说:你绑定到了错误的属性(实际上,你绑定到了一个私有字段,这是不允许的)。我相信你在输出控制台上得到了某种绑定错误,但你忽略了它 :) - Noctis
@Novikov - 这对你来说是双向工作吗?对我来说,它会填充下拉框,但更改下拉框中的选定值不会更改(在你的情况下)Strategy。你是否添加了任何额外的内容? - Erik Thysell
应该是 SelectedItem,但这并不改变我无法绑定它的事实...?如果我理解正确,combobox 包含的是 public IEnumerable<StrategyType> StrategyTypes 的结果 - 这里 SelectedItem 的类型是什么?我猜它不是 StrategyType 而是其他什么东西,是吗? - Erik Thysell
3个回答

6

您试图绑定到一个私有变量,相反,您的枚举应该公开为属性

public IEnumerable<StrategyTypes> StrategyTypes
{
    get
    {
        return Enum.GetValues(typeof(StrategyType)).Cast<StrategyType>();
    }
}

此外,Discosultan已经为您解决了另一个问题。

2
在WPF XAML中将任何枚举数据绑定到组合框的最简单方法: 在窗口或用户控件资源中添加数据提供程序。

xmlns:pro="clr-namespace:TestProject">

<UserControl.Resources>
    <ObjectDataProvider x:Key="getDataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="pro:YourEnumName"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</UserControl.Resources>
<!--ComboBox xaml:-->
<ComboBox ItemsSource="{Binding Source={StaticResource getDataFromEnum}}"/>

0

我在YouTube上找到了一个解决方案。请查看下面的链接:

如何在WPF中将枚举绑定到ComboBox:https://youtu.be/Bp5LFXjwtQ0

该解决方案创建了一个从MarkupExtension类派生的新类,并将此类用作XAML代码中的源。

EnumBindingSourceExtention.cs文件:

namespace YourProject.Helper
{
public class EnumBindingSourceExtention : MarkupExtension
    {
        public Type EnumType { get; private set; }

        public EnumBindingSourceExtention(Type enumType)
        {
            if (enumType == null || !enumType.IsEnum)
            {
                throw new Exception("EnumType is null or not EnumType");
            }
            this.EnumType = enumType;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enum.GetValues(EnumType);
        }
    }
}

View.Xaml 文件:

<Window
    xmlns:helper="clr-namespace:YourProject.Helper"/>
<ComboBox
    ItemsSource="{Binding Source={helper:EnumBindingSourceExtention {x:Type local:TheEnumClass}}}" />

local:TheEnumClass: TheEumClass 应该位于您指定的命名空间中(在本例中,它位于 local 上)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接