views:

903

answers:

2

In my view I have this:

<TextBlock Text="{Binding Title}"/>

which binds to my ViewModel's Title property and this is straightforward and works well:

private string _title;
public string Title
{
    get
    {
        return _title;
    }

    set
    {
        _title = value;
        OnPropertyChanged("Title");
    }
}

However my ViewModel also has the Property "FormFields" which is a StackPanel that contains a number of other UserControls:

private StackPanel _formFields;
public StackPanel FormFields
{
    get
    {
        return _formFields;
    }

    set
    {
        _formFields = value;
        OnPropertyChanged("FormFields");
    }
}

How do I bind this from my view?

In ASP.NET there was a PlaceHolder element, I'm looking for something with the same functionality, e.g.

PSEUDO CODE:

<PlaceHolder Content="{Binding FormFields}"/>
+7  A: 

Firstly, don't. Instead of dictating the UI from your VM, you should be dictating data (the model). In other words, the property type should be ObservableCollection<FormField>. Then your view would bind as follows:

<StackPanel ItemsSource="{Binding FormFields}"/>

Having said that, you can use a ContentPresenter to grab the StackPanel and stick it in the visual tree:

<ContentPresenter Content="{Binding FormFields}"/>

HTH, Kent

Kent Boogaart
Hmmm, ok, I couldn't get it to work with ItemsSource and hence discovered that you can just make a ViewModel Property to be a XAML Element which seemed to be a very useful pattern, will have to rethink this, but the ContentPresenter works well for now, thanks.
Edward Tanguay
A: 

Have you tried using a Border or just a plain Grid?

<Border Content="{Binding FormFields}" />

Still, I'm questioning the design. The Form Fields should live in a view, and the view should be specified in data template which is instantiated based on the view model type. I wouldn't personally do what you're doing in code.

Cheers.

OJ