c# - 如何将组合框绑定到具有类型的扩展类?
问题描述
我在 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.
解决方案
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>
你不应该同时绑定SelectedValue
和SelectedItem
。
推荐阅读
- c# - 只需打印数组 c# 的最后一行
- jasper-reports - 我们可以在 ireport 的详细信息带中包含变量“TOTAL_SUM”吗?
- prometheus - 警报管理器唯一 ID
- alexa - 亚马逊 Alexa:无限期会话
- java - 如何在 Java Swing JTable 中冻结我的最后一列
- android - 如何在不同的imageView上设置List<>中图像src的倍数?
- php - cakephp 管理员前缀资产
- mongodb - 如何通过 mongo objectID 找到多个集合记录
- android - 改造 URL 查询字符串不能有替换块
- php - 使用连接到 MySQL 数据库的 Node.js 路由通过表单进行身份验证