wpf - 如何将 StackPanel 绑定(bind)到我的 ViewModel?

标签 wpf data-binding mvvm

在我看来,我有这个:

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

它绑定(bind)到我的 ViewModel 的 Title 属性和 这很简单,效果很好 :
private string _title;
public string Title
{
    get
    {
        return _title;
    }

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

但是我的 ViewModel 也有属性“FormFields”这是一个包含许多其他用户控件的 StackPanel:
private StackPanel _formFields;
public StackPanel FormFields
{
    get
    {
        return _formFields;
    }

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

从我的角度来看,我该如何绑定(bind)?

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

伪代码:
<PlaceHolder Content="{Binding FormFields}"/>

最佳答案

首先,不要。与其从 VM 口述 UI,不如口述数据(模型)。换句话说,属性类型应该是 ObservableCollection<FormField> .然后您的 View 将按如下方式绑定(bind):

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

这通常在 .Resources 中定义。父元素的部分。即Window.ResourcesWrapPanel.Resources .

话虽如此,您可以使用 ContentPresenterStackPanel并将其粘贴在可视化树中:
<ContentPresenter Content="{Binding FormFields}"/>

关于wpf - 如何将 StackPanel 绑定(bind)到我的 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964170/

相关文章:

WPF,如何在观看 TypeDescriptor 时正确取消 Hook 处理程序

c# - 如何从 WPF 应用程序方法运行 Windows 服务应用程序

c# - 在代码隐藏中修改列表框的数据模板属性

c# - 如何将带有绘图的 Canvas 放置在 ListView 控件的特定列内?

c# - WPF 将集合的集合绑定(bind)到 DataGrid

c# - 当项目更改时,WPF ListBox 不更新绑定(bind)项目的值

javascript - javascript 中 soundcloud 的当前时间和持续时间

c# - 将控件绑定(bind)到 WPF 中的集合/数组中的单个值

c# - 保护条款不触发

c# - 如何使过载变得更简单