在ContentTemplate内时,wpf组合框未绑定到集合
我正在尝试基于属性(combobox或textbox)显示某个控件。所以我实现了这个contentcontrol:在ContentTemplate内时,wpf组合框未绑定到集合,wpf,combobox,contentcontrol,Wpf,Combobox,Contentcontrol,我正在尝试基于属性(combobox或textbox)显示某个控件。所以我实现了这个contentcontrol: <!--<ComboBox MaxWidth="200" Background="#333333" ItemsSource="{Binding ModelObjectWrapper.Values}" Grid.Row="1" Grid.Column="1"/>--> <ContentControl Grid.Row="1" Grid.Co
<!--<ComboBox MaxWidth="200" Background="#333333" ItemsSource="{Binding ModelObjectWrapper.Values}" Grid.Row="1" Grid.Column="1"/>-->
<ContentControl Grid.Row="1" Grid.Column="1">
<ContentControl.Resources>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding ModelObjectWrapper.ObjType}" Value="typeA">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<ComboBox HorizontalAlignment="Left" MaxWidth="200" Background="#333333" ItemsSource="{Binding ModelObjectWrapper.Values, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ModelObjectWrapper.ObjType}" Value="typeB">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBox />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Resources>
</ContentControl>
ContentControl
中根元素的DataContext
是相同ContentControl
的Content
。尝试使用相对资源
绑定到ContentControl
的数据上下文
的属性:
<ComboBox HorizontalAlignment="Left" MaxWidth="200" Background="#333333"
ItemsSource="{Binding DataContext.ModelObjectWrapper.Values, RelativeSource={RelativeSource AncestorType=ContentControl}}"/>
顺便说一句,设置
ItemsSource
绑定到PropertyChanged
的UpdateSourceTrigger
是没有意义的,因为ComboBox
从不设置源属性。感谢mm8提供的解决方案和解释。工作得很好!
<ComboBox HorizontalAlignment="Left" MaxWidth="200" Background="#333333"
ItemsSource="{Binding DataContext.ModelObjectWrapper.Values, RelativeSource={RelativeSource AncestorType=ContentControl}}"/>