如何将StackPanel绑定到ViewModel? [英] How do I bind a StackPanel to my ViewModel?

查看:405
本文介绍了如何将StackPanel绑定到ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有这样的:

In my view I have this:

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

它绑定到我的ViewModel的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");
    }
}

然而,我的ViewModel也有属性 FormFields是一个StackPanel,其中包含一些其他UserControls:

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");
    }
}

如何绑定我的视图?

在ASP.NET中有一个 PlaceHolder 元素,我正在寻找具有相同功能的东西,例如

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

PSEUDO代码

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


推荐答案

首先,不要。您不应该从虚拟机指定UI,而应该是使用数据(模型)。换句话说,属性类型应为 ObservableCollection< FormField> 。那么你的视图将如下绑定:

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:

<ItemsControl ItemsSource="{Binding FormFields}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        <ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

说完了,你可以使用一个 ContentPresenter 抓住 StackPanel 并粘贴在视觉树中:

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

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

这篇关于如何将StackPanel绑定到ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆