WPF Combobox, how to change the DataTemplate of SelectedItem
Martin Han
26
Reputation points
This is my the xaml code of my view:
<v:View x:TypeArguments="local:ShapedSettingsViewModel" x:Name="view"
x:Class="Enigma.Spacial.TestWPF.Visual.ShapedSettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:v ="clr-namespace:Enigma.Spacial.TestWPF.Visual"
xmlns:local="clr-namespace:Enigma.Spacial.TestWPF.Visual"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="200">
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock>ShapedType</TextBlock>
<ComboBox Name="comboBox" Grid.Column="1" ItemsSource="{Binding ViewModel.ShapedTypeOptions,ElementName=view}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShapedTypeName}"></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ComboBox>
</Grid>
<ContentControl Content="{Binding SelectedItem,ElementName=comboBox}"></ContentControl>
</DockPanel>
</v:View>
And this is my view model:
public class ShapedSettingsViewModel : ViewModel {
public ShapedSettingsViewModel() {
}
public IReadOnlyList<ContentControl> ShapedTypeOptions { get; } = new ContentControl[] {
new CircleShapedSettingsView() {
ViewModel = new CircleShapedSettingsViewModel()
},
new RectangleShapedSettingsView() {
ViewModel = new RectangleShapedSettingsViewModel()
}
};
}
All my view classes inherit ContentControl.
When I test my application, the dropdown list of combox box shows strings of ShapedTypeName as espected. However, after selection, and the dropdown disappear, the box's content become the view, not the string.
How can I set the datatemplate for the selected item presenting in the box?
Update, June 8 2022
The views are shown as ItemTemplate, only the string ShapedTypeName is present.
After selection, the item is not shwon as ItemTemplate.
Developer technologies | Windows Presentation Foundation
2,857 questions
Developer technologies | XAML
857 questions
Sign in to answer