WPF以编程方式复制控件

时间:2016-03-27 08:28:56

标签: c# wpf xaml duplicates controls

我创建了一个示例控件,我希望将其复制的次数与我在代码中设置的次数一样多。我想复制整个(code != '400' && code != '401' && code != '500') 控件。

XAML:

<ToggleButton>

现在我手动复制了一次 <WrapPanel Name="varom"> <ToggleButton Margin="10"> <StackPanel Orientation="Horizontal"> <Label Content="Stop sign" /> <Image Width="16" Source="{Binding appbar_stop}" /> </StackPanel> </ToggleButton> <ToggleButton Margin="10"> <StackPanel Orientation="Horizontal"> <Label Content="Stop sign" /> <Image Width="16" Source="{Binding appbar_stop}" /> </StackPanel> </ToggleButton> </WrapPanel> ,但如果我只有一个<ToggleButton>并且我希望获得第二次而不复制xaml代码...

是否可以使用代码复制(复制)<ToggleButton>控件?

C#:

<ToggleButton>

1 个答案:

答案 0 :(得分:0)

型号:

public class ButtonViewModel
{
    public string Caption { get; set; } 
}

public class ViewModel
{
    public ViewModel()
    {
       Buttons = new ObservableCollection<ButtonViewModel>
       {
           new ButtonViewModel { Caption = "Button 1" },
           new ButtonViewModel { Caption = "Button 2" },
           new ButtonViewModel { Caption = "Button 3" },
       };
    }

    public ObservableCollection<ButtonViewModel> Buttons { get; }  
}

XAML:

<ItemsControl ItemsSource="{Binding Buttons}" >
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <ToggleButton Margin="10">
        <StackPanel Orientation="Horizontal">
          <Label Content="{Binding Caption}" />
          <Image Width="16"/>
        </StackPanel>
      </ToggleButton>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
相关问题