【发布时间】:2016-01-13 16:31:05
【问题描述】:
我需要根据特定条件在 ItemsControl 中添加不同的控件(TextBox/CheckBox/ComboBox 等)。 ItemsControl 中的每个 Item 都是一个名称-值对。 Name 始终由 TextBlock 表示,但 Value 可以是任何 UI 控件。 我使用水平对齐的 StackPanel 来表示每个项目。 StackPanel 中的第一个控件仍然是 TextBlock,但第二个控件取决于运行时在 ViewModel 中设置的“ItemDataType”属性。
我遇到的问题是我无法使用带有 ItemDataType 属性的 Style 触发器在 StackPanel 的第二个元素中分配不同的控件。
代码片段:
<UserControl.Resources>
<DataTemplate x:Key="TextBoxTemplate">
<TextBox Text="{Binding Path=DataValue}"/>
</DataTemplate>
<DataTemplate x:Key="ComboBoxTemplate">
<ComboBox ItemsSource="{Binding Path=SelectionList}" SelectedValue="{Binding Path=DataValue,Mode=TwoWay}"/>
</DataTemplate>
<DataTemplate x:Key="CheckBoxTemplate">
<CheckBox IsChecked="{Binding Path=DataValue,Mode=TwoWay}" />
</DataTemplate>
<DataTemplate x:Key="ButtonTemplate">
<Button Content="{Binding Path=DataValue}"/>
</DataTemplate>
<DataTemplate x:Key="dynamicTemplate">
<StackPanel Orientation="Horizontal" Tag="{Binding ItemDataType}">
<TextBlock Text="{Binding Path=DataName,Mode=TwoWay}"/>
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding ItemDataType}" Value="TextBox">
<Setter Property="Template" Value="{StaticResource TextBoxTemplate}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<!-- CONTROL LAYOUT -->
<ItemsControl ItemsSource="{Binding Path=DataList,Mode=TwoWay}" ItemTemplate="{StaticResource dynamicTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
我得到的错误是 DataTemplate 对 ContentControl.Template 属性无效。我知道我的做法是错误的,但我需要帮助以正确的方式做。
谢谢,
RDV
【问题讨论】:
标签: wpf datatemplate itemscontrol contentcontrol