【问题标题】:ComboBox WPF Databinding to a DataView组合框 WPF 数据绑定到数据视图
【发布时间】:2011-03-08 16:06:32
【问题描述】:

假设我的 GUI 上有一个 ComboBox 和 2 个 TextBox 项。我有一个数据视图(城市、邮政编码、街道、ID)。在初始化整个过程时,我用一些数据填充了我的 DataView :)

City 1, 11111, Street 1, 1
City 1, 22222, Street 2, 2
City 1, 33333, Street 3, 3

现在我想将它绑定到我的 ComboBox。 DataView 是一个名为m_dvAdresses 的类成员,但这段代码没有帮助:

ItemsSource="{Binding Source=m_dvAdresses}"
SelectedValuePath="ID"
DisplayMemberPath="Street">

我还想让我的 2 个 ComboBox 项目显示 PostalCode 和 City,这取决于我在 ComboBox 中选择的内容。就像我选择“Street 2”一样,TextBox1 显示“City 1”,TexBox2 显示“22222”......

如何仅在 WPF 代码中绑定所有这些?

【问题讨论】:

    标签: c# wpf data-binding combobox


    【解决方案1】:

    如果m_dvAddressesa Field then WPF cannot bind to it。 WPF 只能绑定到 CLR 属性和 WPF DependencyPropertys。

    public DataView Addresses
    {
         get { return m_dvAddresses; }
    }
    

    顺便说一句,为了获得最丰富的 WPF 体验,请考虑将集合类型设为 ObservableCollection(或 IBindingList 的一些派生类)。这样,对集合本身的所有更改都会适当地发布到 GUI。 编辑:我现在意识到您正在使用完全可绑定的 DataView

    回答你的第二个问题(给定一个ComboBoxx:Name="Address"):

    <TextBox Text="{Binding SelectedItem.City, ElementName=Address}" />
    <TextBox Text="{Binding SelectedItem.Zip, ElementName=Address}" />
    

    【讨论】:

      【解决方案2】:

      您需要做的是将m_dvAddresses 作为@sixlettervariables 提到的类中的属性公开。之后,要从 XAML 访问它,您需要为绑定指定 RelativeSource 属性以指向类本身,如下所示(这里我的控件是 Window):

      ItemsSource="{Binding Addresses, RelativeSource={RelativeSource AncestorType=Window}}"
      Name="cmbAddresses"
      

      对于文本框,您必须按如下方式指定它们的绑定

      <TextBox Name="TextBox1" 
               Text="{Binding SelectedItem.PostalCode, ElementName=cmbAddresses}"/>
      

      第二个文本框类似

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        • 2015-12-12
        • 2014-02-03
        • 2011-08-25
        • 1970-01-01
        相关资源
        最近更新 更多