在 MVVM 中动态创建控件

Dynamically Create Controls in MVVM

我是 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>

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

根据我的评论:

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>