当绑定在标签上工作时,“集合视图”中的“选择器”不会预先选择 MAUI 中的任何值

问题描述 投票:0回答:2

我正在尝试在 2 个可观察的集合之间建立联系:里程碑、类别

在模型“Milestone”上,我有一个属性“SelectedCategory”

public Category SelectedCategory
{
    get => selectedCategory;
    set
    {
        if (selectedCategory != value)
        {
            selectedCategory = value;
            OnPropertyChanged(nameof(SelectedCategory));
        }
    }
}

我在每个里程碑的代码隐藏中选择它:

foreach (var m in Milestones)
{
    m.SelectedCategory = Categories.FirstOrDefault(c => c.IdCategory == m.IdCategory);
}

但是,问题是,当我尝试在选择器中预先选择此类别时,没有预先选择任何内容。 检查完后面的所有代码后,我很确定问题来自 XAML :

<CollectionView Grid.Row="1" Margin="25,10,0,0" ItemsSource="{Binding Milestones}" VerticalOptions="FillAndExpand">
    <CollectionView.ItemTemplate>
        <DataTemplate>

                <Picker Grid.Column="2"
                ItemsSource="{Binding Path=BindingContext.Categories, Source={RelativeSource AncestorType={x:Type local:ModifyProjectPage}}}"
                ItemDisplayBinding="{Binding CategoryName}"
                SelectedItem="{Binding SelectedCategory, Mode=TwoWay}" />   

        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

顺便说一句,绑定正在工作,我可以看到所有类别名称,当我尝试使用标签进行操作时,一切都工作正常。并且控制台也没有报错

<Label Text="{Binding SelectedCategory.CategoryName}" />

没有

Source={RelativeSource AncestorType={x:Type local:ModifyProjectPage}}}
,绑定就无法工作:

<Picker Grid.Column="2"
ItemsSource="{Binding Categories}"
ItemDisplayBinding="{Binding CategoryName}"
SelectedItem="{Binding SelectedCategory, Mode=TwoWay}" /> 
data-binding binding uicollectionview maui
2个回答
0
投票

我遇到了类似的问题,我认为这与 Picker 的实现方式有关,不知何故,代码没有收到您的 SelectedItem 作为 ObservableCollection 的成员,并且只是在 Collection 中找不到它。我通常采取的解决方法是不设置 SelectedItem,而是设置 SelectedIndex。 看看这个问题,我当时对毛伊岛还很陌生,但我认为它可以帮助你。


0
投票

绑定的代码看起来不错。

Picker
控件放置在 DataTemplate 中,并且
ItemsSource
属性绑定到 ViewModel 中的
Categories
。因此,您可以将 Relative Bindings 用于
ItemsSource
Picker

我认为这不是绑定问题的另一个原因是,如果我设置一个小的延迟,则 PreSelected Picker Item 将成功显示。

protected async override void OnAppearing()
{
    base.OnAppearing();
    await Task.Delay(50);

    foreach (var m in viewModel.Milestones)
    {
        m.SelectedCategory = viewModel.Categories.FirstOrDefault(c => c.IdCategory == m.IdCategory);         
    }
}

但这不是一个好的解决方案。我也可以重现这个问题,您可以考虑在 Github 上提出问题。

© www.soinside.com 2019 - 2024. All rights reserved.