C#C
C#7mo ago
46 replies
oke

✅ ComboBox selected item can only be updated from binding property, not the control itself

I'm attempting to use a combo box with a collection of records the user can select from. I can get the items to render in the control, and can set a default value, but the combo box will not update when you select one of the values from the dropdown. I set breakpoints on anything I could think of from the bound property, various
XxxChanged
events, etc.

All I could find online were specific errors, which were solved by reordering the properties, which didn't apply to me because my formatter had done that already.

This is the relevant code:
public sealed record JavaVersionInformation
{
    public Version Version { get; init; }
    public string RawVersion { get; init; }
    public JavaType JavaType { get; set; } // This enum was left out
}

...

public sealed class TheViewModel : ObservableObject // From CommunityToolkit.Mvvm
{
    [ObservableProperty]
    public partial ObservableCollection<JavaVersionInformation> FoundJavaVersions { get; set; } = []; // Populated in the ctor

    [ObservableProperty]
    public partial JavaVersionInformation SelectedJavaVersion { get; set; } // Set after populating FoundJavaVersions. Shows on the ComboBox
}


ui
being WpfUi: https://wpfui.lepo.co/
<ComboBox
    Grid.Column="1"
    ItemsSource="{Binding ViewModel.FoundJavaVersions, Mode=OneTime}"
    SelectedItem="{Binding ViewModel.SelectedJavaVersion, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="j:JavaVersionInformation">
            <ui:TextBlock>
                <Run Text="{Binding JavaType, Mode=OneTime}" />
                <Run Text="{Binding FixedRawVersion, Mode=OneTime}" />
                <Run Text="(" /><Run Text="{Binding RawVersion, Mode=OneTime}" /><Run Text=")" />
            </ui:TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>


The attached image shows what the combo box looks like. The selection doesn't update after clicking an item.
image.png
wpfui.lepo.co
Was this page helpful?