您可以使用一個通用ContentControl,其樣式將選擇(通過觸發器)包含相應控件類型的不同ControlTemplates。
此方法也可以稍微修改爲使用DataTemplates而不是ControlTemplates(可以說是更好的方法)。而不是設置模板屬性(這是一個ControlTemplate),設置ContentTemplate屬性(這是一個DataTemplate),並填充每個DataTemplate與您所需的控制。
<Window x:Class="ControlTypeBasedOnComboBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox Grid.Row="0"
ItemsSource="{Binding Path=ControlTypes}"
x:Name="ControlTypeComboBox"/>
<ContentControl Grid.Row="1">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=ControlTypeComboBox, Path=SelectedItem}" Value="TextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<TextBox/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=ControlTypeComboBox, Path=SelectedItem}" Value="CheckBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<CheckBox/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=ControlTypeComboBox, Path=SelectedItem}" Value="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Button/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
代碼隱藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
視圖模型:
public class ViewModel
{
ObservableCollection<string> controlTypes;
public ViewModel()
{
controlTypes = new ObservableCollection<string>() { "TextBox", "CheckBox", "Button" };
}
public ObservableCollection<string> ControlTypes
{
get { return controlTypes; }
}
}
至於保存/刪除按鈕,還可以綁定命令屬性基於ComboBox的SelectedItem,View Model中的不同ICommand對象。我不知道你需要什麼樣的功能,所以我不知道這是否是必要/合適的。
希望有幫助!