获取动态生成的文本框值MVVM

时间:2013-07-31 14:18:42

标签: silverlight silverlight-5.0

我生成了几个添加到stackpanel列表框项目源

的文本框

现在说,例如生成8个具有唯一名称的框,如何从这些对象中检索值?

这遵循MVVM模式,所以我不能直接调用xaml但需要文本框的值来保存它们

1 个答案:

答案 0 :(得分:1)

您可以在代码隐藏中创建绑定:

for (int i = 0; i < 8; i++)
{
    // create and initialize textbox 
    TextBox textBox = new TextBox();

    // bind Text to "SomeProperty" in your view model
    textBox.SetBinding(TextBox.TextProperty, new Binding("SomeProperty") { Mode = BindingMode.TwoWay }) ;
}

您也可以ItemsControl使用ItemTemplate显示TextBox并绑定到视图模型中的集合。这样,您可以按集合中的元素数控制文本框的数量。