繁体   English   中英

ComboBox WPF数据绑定到DataView

[英]ComboBox WPF Databinding to a DataView

假设我的GUI上有一个ComboBox和2个TextBox项。 我有一个DataView数据(City,PostalCode,Street,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代码中绑定所有这些?

如果m_dvAddressesField,则WPF无法绑定到它 WPF只能绑定到CLR属性和WPF DependencyProperty

public DataView Addresses
{
     get { return m_dvAddresses; }
}

另外,为了获得最丰富的WPF体验,请考虑使用集合类型 ObservableCollection (或 IBindingList某种衍生物)。 这样,对集合本身的所有更改都会适当地发布到GUI。 编辑:我现在意识到你正在使用完全可绑定的DataView

要回答你的第二个问题(给定一个带有x:Name="Address"ComboBox x:Name="Address" ):

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

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

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

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

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

类似于第二个TextBox

希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM