MartinHan-6727 avatar image
0 Votes"
MartinHan-6727 asked HuiLiu-MSFT commented

WPF Combobox, how to change the DataTemplate of SelectedItem

This is my the xaml code of my view:

 <v:View x:TypeArguments="local:ShapedSettingsViewModel" x:Name="view"
              xmlns:v ="clr-namespace:Enigma.Spacial.TestWPF.Visual"
              d:DesignHeight="300" d:DesignWidth="200">
         <Grid DockPanel.Dock="Top">
             <ComboBox Name="comboBox" Grid.Column="1" ItemsSource="{Binding ViewModel.ShapedTypeOptions,ElementName=view}">
                         <TextBlock Text="{Binding ShapedTypeName}"></TextBlock>
         <ContentControl Content="{Binding SelectedItem,ElementName=comboBox}"></ContentControl>

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.

· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,@MartinHan-6727. Welcome Microsoft Q&A.
Did your CircleShapedSettingsView create a new window? How does the view class inherit from ContentControl? Is it possible to show the complete code for CircleShapedSettingsView ? Could you show a screenshot of the problem after selecting the ComboboxItem and describe the gap between the problem and expectations based on the screenshot? And what is the data type of the properties ShapedTypeOptions and ShapedTypeName ?

0 Votes 0 ·

I just added some detail, please take a look.

0 Votes 0 ·
HuiLiu-MSFT avatar image HuiLiu-MSFT MartinHan-6727 ·

Hi,@MartinHan-6727. Based on the code and screenshots you have provided now I cannot reproduce your problem. Could you share a minimal public project that can reproduce the problem for me to analyze?

0 Votes 0 ·

0 Answers