Search code examples
xamlwinui-3.net-7.0

WinUI 3 Desktop Multiple Binds Crash


WinUI 3 Desktop .net 7 WindowsAppSDK 1.2.230313.1

I have a List that is bound to multiple comboboxes with seperate SelectedItem binds. If I were to select either of the comboxes, it works fine, until I select the next ComboBox, it then crashes the application. Any explaination?

Also a side problem, within the list, I have the ComboBoxItem IsSelected=True, that is not being acknowledged or bound. How do I fixed that?

public List<ComboBoxItem> Countries
{
    get => Extensions.GetCountries();
}

public static List<ComboBoxItem> GetCountries() => new() {
    new() { Name= "AF", Content= "Afghanistan" },
    new() { Name= "AL", Content = "Albania" },
    new() { Name= "DZ", Content = "Algeria" },
    new() { Name= "AS", Content= "American Samoa" },
    new() { Name= "AD", Content= "Andorra" },
    new() { Name= "AO", Content= "Angola" },
    new() { Name= "AI", Content= "Anguilla" },
    new() { Name= "AQ", Content= "Antarctica" },
    new() { Name= "AG", Content= "Antigua and Barbuda" },
    new() { Name= "AR", Content= "Argentina" },
    new() { Name= "AM", Content= "Armenia" },
    new() { Name= "AW", Content= "Aruba" },
    new() { Name= "AU", Content= "Australia" }
};
<ComboBox
    Header="Country"
    SelectedItem="{x:Bind p.ViewModel.Entity.Individual.Address.Country}"
    ItemsSource="{x:Bind p.ViewModel.Countries}" />
                
<ComboBox
    Header="Country"
    SelectedItem="{x:Bind p.ViewModel.Entity.Company.Address.Country}" 
    ItemsSource="{x:Bind p.ViewModel.Countries}" />

Solution

  • You can't have the same UI instances (ComboBoxItem) in different parents (ComboBox). You also should try to keep ViewModels without UI elements.

    Instead of ComboBoxItems, you can use a Country class:

    public class Country
    {
        public string Name { get; set; } = string.Empty;
    
        public string Code { get; set; } = string.Empty;
    }
    
    <ComboBox
        Header="Country"
        ItemsSource="{x:Bind ViewModel.Countries}"
        SelectedItem="{x:Bind ViewModel.Entity.Company.Address.Country}">
        <ComboBox.ItemTemplate>
            <DataTemplate x:DataType="local:Country">
                <TextBlock Text="{x:Bind Name}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>