您可以使用一个通用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对象。我不知道你需要什么样的功能,所以我不知道这是否是必要/合适的。
希望有帮助!