【问题标题】:How do I bind a string to a DataContext while having multiple DataContexts?如何在拥有多个 DataContext 时将字符串绑定到 DataContext?
【发布时间】:2020-07-24 06:55:01
【问题描述】:

我正在使用自定义库,并且必须将 SQL 连接字符串绑定到 SqlGeometryDataAdapter。如果我使用以下方法,我无法声明多个 DataContext,因为除非我设置 ConnectionString as

,否则代码将无法编译

="{绑定}"/>

而不是

="{绑定 WKT}"/>


XAML:

<dxm:VectorLayer x:Name="WKT_Layer" DataLoaded="WKT_Layer_DataLoaded">
    <dxm:SqlGeometryDataAdapter x:Name="WKT_Adapter"
                                SqlText = "SELECT [WKT], [SID],[FILL],[STROKE] FROM [TLORIS] ORDER BY [SID]"
                                SpatialDataMember = "WKT"
                                ConnectionString="{Binding}"/>
</dxm:VectorLayer>

XAML.CS:

public MainWindow()
{
    InitializeComponent();
    DataContext = WKT;
}

public string WKT { get; } = "Data Source=127.0.0.1; Initial Catalog=TESTDB; Connection Timeout=2; Persist Security Info=True; User=SA; Password=PASSWORD";

我可以通过创建一个类并在其中声明一个字符串来规避这个问题,但是必须有更简单的方法来完成这个吗?


XAML:

<dxm:VectorLayer x:Name="WKT_Layer" DataLoaded="WKT_Layer_DataLoaded">
    <dxm:SqlGeometryDataAdapter x:Name="WKT_Adapter"
                                SqlText = "SELECT [WKT], [SID],[FILL],[STROKE] FROM [TLORIS] ORDER BY [SID]"
                                SpatialDataMember = "WKT"
                                ConnectionString="{Binding WKT}"/>
</dxm:VectorLayer>

XAML.CS:

public MainWindow()
{
    InitializeComponent();
    DataContext = SQLConnection.GetSQLConnection();
}

class SQLConnection
{
    public string WKT { get; set; }

    public static SQLConnection GetSQLConnection()
    {
        return new SQLConnection() { WKT = "Data Source=127.0.0.1; Initial Catalog=TESTDB; Connection Timeout=2; Persist Security Info=True; User=SA; Password=PASSWORD;" };
    }
}

【问题讨论】:

  • DataContext = WKT; 没有意义。为了绑定到 MainWindow 的 WKT 属性,设置DataContext = this;
  • @Clemens DataContext = WKT;只要我离开 ConnectionString="{Binding}"/> 就可以工作,这使得它更加混乱,因为从未声明过绑定。
  • "{Binding}" 直接绑定到当前 DataContext,然后包含 WKT 属性的值。

标签: wpf binding devexpress datacontext


【解决方案1】:

答案:

DataContext = WKT;没有意义。为了绑定到 MainWindow 的 WKT 属性,设置 DataContext = this;。 @克莱门斯

【讨论】:

  • 虽然这给了你现在的答案,但这种方法是完全错误的。您应该将 View 和 ViewModel 分开。创建一个适当的 ViewModel 类并将该类设置为您的 DataContext。
  • 你会说我最初问题中的第二种方法合适吗?
  • 我没有看到第二种方法,但你当然应该阅读 MVVM
猜你喜欢
  • 2010-10-16
  • 2011-05-19
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多