Set up a Data Connection Between the List and the Data Source Collection (Compact 7)
3/12/2014
After you create a data source collection, you must establish a data connection by expanding the responsibilities of the XRObservableCollection<ItemType> object to include the following roles:
- The data context for your application
- The items source for the list
To set up a data connection between the list and the data source collection
In your subproject, open the source code file where you want to add functionality for setting up the data connection. For example, in Solution Explorer, browse to Subprojects\<Subproject Name>\Source files, and open MainPage.cpp.
To obtain a pointer to the root element of the visual host, call IXRVisualHost::GetRootElement, as shown in the following code example.
HRESULT App::OnStartup() { HRESULT hr = S_OK; IXRFrameworkElementPtr pRoot; hr = m_pVisualHost->GetRootElement(&pRoot); if (SUCCEEDED(hr)) { // TODO: Add one time initialization code here. } return hr; } // OnStartup
To obtain a pointer to the list that you designed earlier in this tutorial, call IXRFrameworkElement::FindName on the root element, as shown in the following code example. If you imported an Expression Blend project, this step is autogenerated for all XAML objects with x:Name properties.
// ============================================================================ // WARNING: DO NOT EDIT THIS ALWAYS-GENERATED CODE // ============================================================================ HRESULT MainPage::InitializeComponent() { HRESULT hr = E_FAIL; FindName(L"LayoutRoot", &m_pLayoutRoot); FindName(L"EmployeeListBox", &m_pEmployeeListBox); if (m_pLayoutRoot && m_pEmployeeListBox ) { hr = S_OK; } return hr; }
Create an XRValue object instance of type VTYPE_ENUMERABLE.
To convert the XRObservableCollection<ItemType> object instance into an XRValue object, call XRValue::SetValue(IXREnumerable, bool).
To set the data context, call IXRFrameworkElement::SetDataContext on the root element of the visual host, and pass the XRValue object as the Value parameter, as shown in the following code example.
static HRESULT BindView(IXRFrameworkElement* pView) { HRESULT hr = S_OK; if(!m_pModel) { hr = CreateModel(); } if(SUCCEEDED(hr)) { // Set m_pModel to the DataContext of the UserControl hr = pView->SetDataContext(m_pModel); } return hr; }
Note
For applications that display data from multiple data source collections, call IXRFrameworkElement::SetDataContext on each list, user control, or content holder that will display the data stored in each collection.
To set the data collection as the source of items displayed in the list, call the derived method IXRItemsControl::SetItemsSource on the IXRListBox pointer.
Note
This step is equivalent to adding an ItemsSource attribute to a ListBox element in XAML.