XAML WinUI 3桌面多个绑定崩溃

toiithl6  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(128)

WinUI 3桌面.net 7 WindowsAppSDK 1.2.230313.1
我有一个列表,它绑定到多个组合框与单独的SelectedItem绑定。如果我选择任何一个组合框,它的工作正常,直到我选择下一个组合框,它然后崩溃的应用程序。任何解释?
还有一个附带问题,在列表中,我有ComboBoxItem IsSelected=True,它没有被确认或绑定。我如何修复它?

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}" />
z6psavjg

z6psavjg1#

不同父代(ComboBox)中不能有相同的UI示例(ComboBoxItem),同时要尽量保留没有UI元素的ViewModels
可以使用Country类代替ComboBoxItems

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>

相关问题