2013-02-01 49 views
1

我必须使用WCF服务从数据库检索值,并使用ID类型值填充名为“类型”的下拉列表(使用可观察集合来绑定此值)。如何根据WPF中的数据类型更改控制点

应该有另一个由数据模板/控件模板控制的控件,它将根据所选类型显示。例如如果选择了文本框类型,那么文本框应该显示一些默认值。

InputType文本框 - 这将用于在数据库中创建新类型。使用保存按钮保存值。

删除按钮 - 这应该从DataBase中删除选定的类型。

我完成了DataBase Stuff和所有,但我应该如何更改控件取决于XAML中的数据类型?

回答

2

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

希望有帮助!