在用户界面上动态添加UserControl

时间:2013-08-27 18:28:17

标签: wpf xaml mvvm grid itemscontrol

在我的WPF应用程序中,我需要以行和列的形式发布n个用户控件。我的用户控件就像

My user control is like

行数可以是n,而列数可以是1或2,具体取决于用户选择使用的视图。

这是包含我的UserControls

的集合
private Collection<TemplateView> _templates;
public Collection<TemplateView> Templates { get { return _templates; } set { _templates = value; } }

这是我使用的XAML代码。

<ItemsControl ItemsSource="{Binding Templates}">
      <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                  <UniformGrid Columns="{Binding NumColumns}" />
            </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
       <ItemsControl.ItemContainerStyle>
           <Style>
                <Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
                <Setter Property="Grid.Row" Value="{Binding RowIndex}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
              <DataTemplate>
                   <v:TemplateView Content="{Binding }" />
              </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

v:TemplateView是UserControl,其n复制需要在行/列中发布。

以下是一些显示UserControl控件绑定的XAML。

 <Label Content="{Binding Title, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
 <Label Content="{Binding Type, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
 <TextBlock><Hyperlink Command="{Binding DetailsViewCommand}">Details</Hyperlink>
        </TextBlock>
 <TextBlock><Hyperlink Command="{Binding AddCommand}">Add</Hyperlink>

这是我的UserControl的VIewModel代码

  private ICommand _detailsViewCommand;
    public ICommand DetailsViewCommand { get { return _detailsViewCommand ?? (_detailsViewCommand = new RelayCommand(DetailsView)); } }

    public void DetailsView()
    {

    }

    private ICommand _addCommand;
    public ICommand AddCommand { get { return _addCommand ?? (_addCommand = new RelayCommand(Add)); } }

    private void Add()
    {

    }

    private string _layerType;
    public string LayerType
    {
        get { return _layerType; }
        set { _layerType = value; }
    }

    private string _title;
    public string Title
    {
        get { return _title; }
        set { _title = value; }
    }

此UserControl的所有副本将在标签和图像中携带不同的信息。 因此,需要在userControl的ViewModel中知道,当用户按下Details按钮时,单击了UserControls(或Templates Collection中的哪个项目)。

以上XAML和代码并没有告诉我单击“详细信息”按钮时单击了哪个项目/用户控件。那么我该如何完成这两项任务呢?

任何帮助将不胜感激。

由于

0 个答案:

没有答案