【问题标题】:How to bind an Enum from ViewModel to ComboBox - twoway如何将 Enum 从 ViewModel 绑定到 ComboBox - 双向
【发布时间】:2016-08-07 16:29:04
【问题描述】:

[已解决]:我在下面的答案中提供了一个工作示例。


[SO][1] 上的相关主题

我在这里阅读了很多线程,如何将枚举绑定到组合框。 我让它与另一种使用 MarkupExtension 的方法一起工作! 但是我没有可用的双向绑定。

我想将它绑定到我的 ViewModel 的 Enum 属性。

当我尝试这种方法时:

 <Window.Resources>
    <ObjectDataProvider MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}"
                        x:Key="DetailScopeDataProvider">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:DetailScope" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

这里还有一个问题是,VS intellisense 没有为我提供这个:

系统:枚举

我也不知道要设置组合框的 ItemSource 和 SelectedValue 属性。

【问题讨论】:

  • 您是否使用xmlns: 属性声明了sys 命名空间?请提供一个良好的minimal reproducible example 可靠地重现您的问题。很可能是某种印刷错误,但如果没有好的 MCVE,我们甚至无法确定您到底犯了什么错误。
  • 我解决了系统问题。我的主要问题是双向绑定。我将快速创建一个示例并上传它...
  • 因为,例如,当我在文本框中输入一些字符时,它们会立即更新为视图模型。当我更新文本框的 viewmodel 属性时,视图会在没有任何进一步编码的情况下更新。对于从 viewmodel 的 enum 属性获取其值的组合框,我想要的相同
  • “在这里你可以下载我准备的示例项目”——这不是 Stack Overflow 的工作方式。如您所知,接近 2000 个代表自己,每个问题都必须是独立的,具有良好的 minimal reproducible example 可以可靠地重现您正在处理的任何问题或问题,并且来自问题作者的信息属于问题发布本身,而不是 cmets。评论是其他人要求您改进问题的一种方式,但这些改进属于问题本身。
  • 改进并回答了! ;-)

标签: c# wpf data-binding visual-studio-2015


【解决方案1】:

好的,搞定了。

ObjectDataProvider 有一个 ObjectType 属性。因为我想使用我的视图模型的枚举属性作为组合框的数据源。 本例中的对象类型为:

系统.枚举

它位于 mscorlib 程序集的 System 命名空间中。 因此,我们必须在 XAML 中添加导入命名空间:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

这里我把整个代码贴出来供大家参考:

Test.xaml(window):

<Window x:Class="WpfTrash.Test"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTrash"
   -->> xmlns:sys="clr-namespace:System;assembly=mscorlib" <<--
        mc:Ignorable="d"
        Title="Test" Height="300" Width="300">
    <Window.Resources>
        <local:MyEnumToStringConverter x:Key="MyEnumConverter" />
        <ObjectDataProvider x:Key="odp" MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type  TypeName="local:TheEnum"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
    <StackPanel>
        <TextBox x:Name="txtTheInt" Text="{Binding Path=TheInt}"/>
        <TextBox x:Name="txtTheString" Text="{Binding Path=TheString}"/>
        <!--<ComboBox x:Name="cboTheEnum" DataContext="{StaticResource SortedEnumView}" ItemsSource="{Binding}"/>-->
        <ComboBox x:Name="cboTheEnum" ItemsSource="{Binding Source={StaticResource odp}}" SelectedValue="{Binding Path=TheEnum, Converter={StaticResource MyEnumConverter}}"/>
        <Button x:Name="button" Content="Button" Click="button_Click"/>
    </StackPanel>
</Window>

Test.xaml.cs

namespace WpfTrash
{
    /// <summary>
    /// Interaction logic for Test.xaml
    /// </summary>
    public partial class Test : Window
    {
        MyClass vm = new MyClass();
        public Test()
        {
            InitializeComponent();
            this.DataContext = vm;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            var selecteditem = (TheEnum)Enum.Parse(typeof(TheEnum), cboTheEnum.SelectedItem.ToString(), true);
        }
    }
}

视图模型:

public class MyClass : INotifyPropertyChanged
{
    public int TheInt { get; set; }
    public string TheString { get; set; }

    TheEnum theEnum;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public TheEnum TheEnum
    {
        get
        {
            return theEnum;
        }

        set
        {
            theEnum = value;
            NotifyPropertyChanged("TheEnum");
        }
    }
}

枚举定义:(不是类定义的一部分)

public enum TheEnum
{
    A, B, C, D
}

转换器:

public class MyEnumToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (TheEnum)Enum.Parse(typeof(TheEnum), value.ToString(), true);
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 2017-01-05
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    相关资源
    最近更新 更多