How to pass data between controls and persist the values in WPF
I am stuck on how to pass data from one control to another. If I have a listbox control and the Contol Item contains a datatemplate which renders out 5 fields ( first name, last name, email, phone and DOB) all of which come from an observable collection. How can I allow the user to select a listbox item and have the valuesbe stored within a new listbox control?
Is this done through开发者_StackOverflow社区 the creation of a new collection or is there a more simple way to bind these values to a new control?
thank you,
If it is not too late, I would strongly recommend that you use the MVVM pattern. The problem you are facing is typical for WPF without a decent presentation model and wont be the last one.
Using MVVM you would pass data between controls/views through the ViewModel. In your example you would have a PersonViewModel with an ObservableCollection containing first name, last name, email and DOB. Additionally it would have a property SelectedItem. This property can be bound to in a lot of different controls/views without them having to know each other.
Let's say you have a:
<ListBox Name="DemoList" ItemsSource="{Binding ...}">
<ListBox.ItemTemplate>
...
</ListBox.ItemTemplate>
</ListBox>
And another control, maybe a TextBox:
<TextBox Text="I want to bind this to the Email property" />
You can achieve this pretty easily, with:
<TextBox Text="{Binding ElementName=DemoList, Path=SelectedItem.Email}" />
Note the ElementName property of the Binding. This allows you to bind relative to another control, and in this case you want the SelectedItem of your ListBox. SelectedItem will contain an element of the collection in the ItemsSource (or null if nothing is selected), so you can then bind to its properties.
It gets more complex if you want to support multiple selection, but it doesn't sound like this is a requirement for you.
精彩评论