首页 > 解决方案 > 如何将组合框绑定到具有类型的扩展类?

问题描述

我在 wpf 中有一个组合框,想将它绑定到对象的属性。我的问题是,这个属性是一个基类,可以是两种具体类型。

这些是我的课:

    public abstract class Database
    {
        public DBTypes Type { get; set; }
        public abstract void connect();

        public abstract void disconnect();

        public abstract void initDB();


        public Database()
        {

        }
    }

 public class OracleDB : Database
    {
        public string Sid { get; set; }
        public string User { get; set; }
        public string Password { get; set; }

        private OracleConnection m_dbConnection;

        public OracleDB()
        {
            Type = DBTypes.ORACLE;
        }

        public OracleDB( string sid, string user, string passwd )
        {
            Sid = sid;
            User = user;
            Password = passwd;
        }
        .
        . 
        .
}

    public class SqliteDB : Database
    {
        public string DBFile { get; set; }

        private SQLiteConnection m_dbConnection;

        public SqliteDB()
        {
            DBFile = "database.db";
            Type = DBTypes.SQLITE;
        }

        .
        .
     }
}

 public enum DBTypes
    {
        ORACLE,
        SQLITE
    }

WPF部分是:

<ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type System:Enum}" x:Key="EnumValues">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="lib:DBTypes" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

.
.
.

<ComboBox x:Name="DBTyp"  Grid.Column="2" Grid.Row="0" HorizontalAlignment="Stretch" 
                      VerticalAlignment="Center" SelectedIndex="0" 
                      ItemsSource="{Binding Source={StaticResource EnumValues}}"
                      SelectedValue="{Binding Path=DbSettings.Type}"
                      SelectedItem="{Binding Path=DbSettings}">
            </ComboBox>

DbSettings 是数据库类型的属性。

那么,当从组合框中选择另一个条目时,如何实现这一点,选择正确的对象?

随着我的代码我得到

Cannot convert 'SQLITE' from type 'DBTypes' to type 'Database' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: TypeConverter kann nicht von DBTypes konvertieren.

标签: c#wpfcomboboxbinding

解决方案


SelectedItem将属性绑定到DbSettings.Type

<ComboBox x:Name="DBTyp" Grid.Column="2" Grid.Row="0" HorizontalAlignment="Stretch" 
          VerticalAlignment="Center" SelectedIndex="0" 
          ItemsSource="{Binding Source={StaticResource EnumValues}}"
          SelectedItem="{Binding Path=DbSettings.Type}">
</ComboBox>

你不应该同时绑定SelectedValueSelectedItem


推荐阅读