views:

53

answers:

2

I have a listbox in WPF that is in the Layout Root.

I also have a Frame that is in the Layout Root as well.

The listbox is composed of items that have a string(Name) and a framework element(UI).

How do I bind the frame's content to be the UI property of the listbox's selected item property?

If you need a codebehind, how would you do this in MVVM

A: 

It sounds as you want to display list of objects and details for selected object. If I am right, solution in MVVM may be following:

<ListView ItemsSource="{Binding ObjectsList}" IsSynchronizedWithCurrentItem="True" />

<ContentControl Content="{Binding ObjectsList}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <!-- details template -->
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl> 
darja
A: 

I used a ContentControl instead of Frame since I had problem binding to Content property, I never got it to refresh after binding changed. I didn't do proper MVVM, Data should not be hosted inside the view.

XAML:

<Window.Resources>
    <CollectionViewSource x:Key="CVS" Source="{Binding}" />
</Window.Resources>

<StackPanel DataContext="{Binding Source={StaticResource CVS}}">
    <ListBox
        ItemsSource="{Binding}"
        IsSynchronizedWithCurrentItem="True"
        DisplayMemberPath="Name">
    </ListBox>
    <ContentControl Content="{Binding Path=UI}" />
</StackPanel>

Code behind:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace BindDemo
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            Data = new List<DataItem>();
            Data.Add(new DataItem("TextBox", new TextBox(){ Text="hello" }));
            Data.Add(new DataItem("ComboBox", new ComboBox()));
            Data.Add(new DataItem("Slider", new Slider()));

            DataContext = Data;
        }

        public List<DataItem> Data
        {
            get; private set; 
        }
    }

    public class DataItem
    {
        public DataItem(string name, FrameworkElement ui)
        {
            Name = name;
            UI = ui;
        }

        public string Name { get; private set; }
        public FrameworkElement UI { get; private set; }
    }
}
Wallstreet Programmer