Udostępnij za pośrednictwem


Databind selected items across different pages in XAML

In my last post, I show how to databind selectedItems in a listbox in the same windows. This post I show how to databind selectedItem accross different pages.

When databinding data across different  windows/pages/screens, we can't refer to the listbox directly, so we need a small help: DataStore.
The attached solution is a WPF Sketchflow solution. Inside  \bindingScreen\bindingScreen\bindingScreenScreens , there are 2 screens, Screen1 has a listbox databound to a sample datasource, Screen2 has textblocks that display values of the selectedItem of the listbox in Screen1. Assuming there is a collection type of data, I used a SampleDataSource for demonstration.

First: -- Create a dataStore (named SelectedItemData in this solution) from the datapane, add properties with matching names to the properties of the collection in SampleDataSource. Notices that datastore properties support only string, boolean and number data types.

On Screen1:
To do that on Blend UI,  drag SetDataStoreValueAction from Assets pane Behaviors to the listbox, on Properties pane, pick EventName to be "SelectionChanged", pick the Property name that need to be databound, select the "Advance options" menu besides Value and select "Element property binding..", mouse point to the listbox then click, then select "SelectedItem"
Important: Then you have to edit the xaml of the SetDataStoreValueAction for the matching property name:
change: Value="{Binding SelectedItem, ElementName=listBox1}"
to: Value="{Binding SelectedItem .Property1, ElementName=listBox1}"
Repeat the above steps for each databinding property

To do that on code behind, you may add EventHandler to the listbox: SelectionChanged="SetProperty3"
private void SetProperty3(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{ ((Expression.Blend.DataStore.SelectedItemData.SelectedItemData)this.Resources["SelectedItemData"]).Property3
= ((Expression.Blend.SampleData.SampleDS.Item)(this.listBox1.SelectedItem)).Property3;
}
Notice that this.Resources["SelectedItemData"] can be Application.Current.Resources["SelectedItemData"] depends on your project scope.

On Screen2:
Select Detail mode on datapane, multi-select properties on the datastore. drag then drop to the artborad, Blend would generate necessary xaml code for you.
Verify the layoutroot has such attribute: DataContext="{Binding Source={StaticResource SelectedItemData}}"

Hit F5 to test run, when you select an item on Screen1 listbox, its values would display on Screen2

Same technic of using DataStore is applicable for databinding data across different windows/pages/screens.

bindingScreen.zip