简体   繁体   中英

ComboBox WPF Databinding to a DataView

Lets say I have one ComboBox and 2 TextBox items on my GUI. And I have one DataView with data (City, PostalCode, Street, ID). While initializing the whole thing I fill my DataView with some data :)

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

Now I want to bind this to my ComboBox. DataView is a Class Member called m_dvAdresses , but this code doesnt help:

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

Also I want to have my 2 ComboBox items to show PostalCode and City, depending on what to i pick in my ComboBox. Like if I pick "Street 2", TextBox1 show me "City 1" and TexBox2 show me "22222"...

How can I bind all of them ONLY in the WPF code?

If m_dvAddresses is a Field then WPF cannot bind to it . WPF can only bind to CLR Properties and WPF DependencyProperty s.

public DataView Addresses
{
     get { return m_dvAddresses; }
}

As an aside, in order to get the richest WPF experience, consider making the collection type ObservableCollection (or some derivative of IBindingList ). This way all changes to the collection itself are posted to the GUI appropriately. Edit: I realize now that you're using DataView which is fully bindable.

To answer your second question (given a ComboBox with x:Name="Address" ):

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

what you need to do is have m_dvAddresses exposed as a property from your class as mentioned by @sixlettervariables. after that, to access it from XAML, you need to specify the RelativeSource property for the binding to point to the class itself as follows (here my control is a Window ):

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

For the text boxes, you have to specify their bindings as follows

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

similar for the second TextBox

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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