简体   繁体   English

动态文本框绑定

[英]Dynamic text boxes binding

I am trying to make a form of sorts where the user will have the option to press a button to dynamically add more text boxes, with each text box to contain the path of a directory to exclude from a search. 我试图做一种形式的用户可以选择按下按钮动态添加更多文本框,每个文本框包含要从搜索中排除的目录的路径。 This is relatively trivial using code-behind, but my problem is doing it in proper MVVM. 使用代码隐藏这是相对微不足道的,但我的问题是在适当的MVVM中进行。

The general markup for the structure is: 该结构的一般标记是:

<ScrollViewer >
    <StackPanel>
        <DockPanel LastChildFill="False">
            <TextBox DockPanel.Dock="Left"/>
            <Button DockPanel.Dock="Right"
                    Content="+"/>
        </DockPanel>
    </StackPanel>
</ScrollViewer>

Clicking the button will add a new DockPanel with a TextBox and Button to the StackPanel . 单击该按钮将向StackPanel添加带有TextBoxButton的新DockPanel All buttons but the bottom-most will change to a minus sign. 除最底部以外的所有按钮都将变为减号。 How can I somehow bind to the text of all the text boxes? 我怎么能以某种方式绑定到所有文本框的文本?

As an aside, once/if I get this working, would it be better to make it into its own component? 顺便说一句,一旦/如果我得到这个工作,将它变成自己的组件会更好吗?

Quick pseudo-code to get you started: 快速伪代码让您入门:

cs (view model): cs(查看模型):

// INotifyPropertyChanged if you need, as well as full-properties with notification
public class Item
{
    public string Text {get; set;}
}

public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>();

void OnCommandAdd() => Items.Add(new Item());

xaml (view): xaml(查看):

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Text}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The idea is to use control able to display list (eg ItemsControl ) and collection of items in view model. 我们的想法是使用控件能够在视图模型中显示列表(例如ItemsControl )和项目集合。 Adding new element to view is done by adding item to that collection. 通过向该集合添加项目来向视图添加新元素。

All TextBox es will have Text bound to corresponding property of item. 所有TextBox都将Text绑定到item的相应属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM