简体   繁体   English

在MVVM中动态创建控件

[英]Dynamically Create Controls in MVVM

I am pretty new to WPF. 我是WPF的新手。 I am trying to create controls dynamically in MVVM but controls are not rendered on view. 我正在尝试在MVVM中动态创建控件,但是控件未在视图上呈现。 I want some number of label and textbox to be created on view. 我希望在视图上创建一些标签和文本框。

Below is my code: 下面是我的代码:

Model Code 型号代码

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

    public string KeyValue
    {
        get;
        set;
    }
}

ModelView Code ModelView代码

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);

    }
}

View Code(Which is user control) 查看代码(是用户控制的)

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

When view renders, I can only see empty textbox. 视图渲染时,我只能看到空的文本框。 I cannot understand what is wrong..? 我不明白怎么了..?

As per my comment: 根据我的评论:

The DataTemplate receives an individual item as its DataContext , therefore you only need to include item level property names within your binding paths like: 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>

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

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