我需要根據一定的條件在ItemsControl中添加不同的控件(TextBox/CheckBox/ComboBox等)。 ItemsControl中的每個項目都是名稱 - 值對。名稱始終由TextBlock表示,但Value可以是任何UI控件。 我使用水平對齊的StackPanel來表示每個項目。 StackPanel中的第一個控件仍然是TextBlock,但第二個控件依賴於ViewModel在運行時設置的「ItemDataType」屬性。在ItemsControl中添加不同的控件
我遇到的問題是,我無法使用帶有ItemDataType屬性的樣式觸發器在StackPanel的第2個元素中分配不同的控件。
代碼段:
<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