【问题标题】:Dynamically Create Controls in MVVM在 MVVM 中动态创建控件
【发布时间】:2016-11-17 15:41:21
【问题描述】:

我对 WPF 很陌生。我正在尝试在 MVVM 中动态创建控件,但控件未呈现在视图中。我希望在视图中创建一些标签和文本框。

下面是我的代码:

型号代码

public class MyModel
{
    public string KeyName
    {
        get;
        set;
    }

    public string KeyValue
    {
        get;
        set;
    }
}

模型查看代码

public class MyViewModel
{
    private ObservableCollection<MyModel> propertiesList = new ObservableCollection<MyModel>();
    public CustomWriterViewModel()
    {

       GetMyProperties()

    }


    public ObservableCollection<MyModel> Properties
    {
        get { return propertiesList; }
    }

    private void GetMyProperties()
    {
        MyModel m = new MyModel();
        m.KeyName = "Test Key";
        m.KeyValue = "Test Value";
        MyModel.Add(m);

    }
}

查看代码(即用户控制)

<Grid>
    <ItemsControl ItemsSource="{Binding Properties}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type cw:MyModel}">
                <StackPanel Orientation="Horizontal">
                    <Label Margin="10" Content="{Binding Properties.KeyName}"></Label>
                    <TextBox Margin="10" Text="{Binding Properties.KeyValue}" Width="250"></TextBox>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

当视图呈现时,我只能看到空文本框。我不明白出了什么问题..?

【问题讨论】:

  • 您没有在propertiesList 集合中添加任何内容。
  • MyModel.Add(m); wat。在您使用调试器单步执行代码时提供帮助。 msdn.microsoft.com/en-us/library/sc65sadd.aspx
  • 在 propertiesList 中添加了项目,但仍然没有效果。问题还是一样。
  • 我觉得只有数据模板有问题。我在 ProperiesList 中又添加了一项。在这种情况下,我可以看到两个空文本框。
  • 您应该将绑定更改为简单的{Binding KeyName} 而不指定属性。由于它在 DataTemplate 中,因此各个 VM 已经是 DataContext。

标签: c# wpf mvvm data-binding datatemplate


【解决方案1】:

根据我的评论:

DataTemplate 接收单个项目作为其 DataContext,因此您只需在绑定路径中包含项目级别属性名称,例如:

<DataTemplate DataType="{x:Type cw:MyModel}">
    <StackPanel Orientation="Horizontal">
         <Label Margin="10" Content="{Binding KeyName}"></Label>
         <TextBox Margin="10" Text="{Binding KeyValue}" Width="250"></TextBox>
    </StackPanel>
</DataTemplate>

【讨论】:

  • 您可以在输出窗口中识别此类绑定错误。此类错误类似于System.Windows.Data Error: 40 : BindingExpression path error:
猜你喜欢
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多