XAML 如何更改Maui中CollectionView的GridItemsLayout中所选项目的背景颜色?

li9yvcax  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(410)

我正在尝试设置CollectionView中所有选定项的背景色,我正在为这些项使用GridItemsLayout。如果在CollectionView的DataTemplate here中使用网格布局,我已经看到了更改背景色的方法。但是,我试图通过使用CollectionView固有的GridItemsLayout功能来简化编码。我一直在想一定有一个简单的方法来完成我所错过的。
下面是我当前的XAML,它使用详细的背景色来进行项目选择。

<ScrollView>
        <CollectionView x:Name="BrandsToUseCollectionView" ItemsSource="{x:Static vm:BrandsToUseVM.AllBrandNames}"
                        SelectionMode="Multiple" SelectedItems="{Binding BrandNamesSelected}"
                        SelectionChanged="OnBrandSelectionChanged" Margin="15,15,15,0">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Span="2" Orientation="Vertical" VerticalItemSpacing="10" HorizontalItemSpacing="15" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Label FontAttributes="Bold" Padding="0,7,0,0" HeightRequest="40" VerticalOptions="Center"
                               HorizontalOptions="Center" FontSize="Medium" Text="{Binding .}">
                    </Label>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ScrollView>

虽然我可以将<Grid>插入到DataTemplate中并使用VisualStateManager作为一种变通方法,但我希望你们中经验丰富得多的开发人员能够在现在和将来使用Xaml或(如果需要)在代码隐藏中使这一过程对我和其他人来说更简单。

qcuzuvrc

qcuzuvrc1#

我不知道确切的细节,但我假设OnBrandSelectionChanged会得到一个已更改项的列表。
Color BrandBackgroundColor属性添加到BrandName类中。
如果BrandName当前只是string,定义一个类,并使当前字符串成为其属性之一,然后将Selected转换为颜色。
比如:

... OnBrandSelectionChanged(...)
{
  // ??? I don't know parameters for this method.
  // for each changed item ...
  foreach (BrandName brandName in ???)
  {
    // How does OnBrandSelectionChanged see which are selected, which are unselected?
    bool selected = ...;
    brandName.SetSelected(selected);
}

...

public ObservableCollection<BrandName> AllBrandNames ...
...

class BrandName : ObservableObject
{
  // --- Put your existing string here. ---
  public string Name
  {
    get => name;
    set => SetProperty(ref name, value);
  }
  private string name;

  // --- code for SetSelected and BrandBackgroundColor ---
  public void SetSelected(bool selected)
  {
    BrandBackgroundColor = selected ? MySelectedColor : MyDefaultBackgroundColor;
  }

  static Color MySelectedColor = ...;
  static Color MyDefaultBackgroundColor = ...;

  public Color BrandBackgroundColor {
    get => backgroundColor;
    set => SetProperty(ref backgroundColor, value);
  }
  private Color backgroundColor;
}
<ListView.ItemTemplate>
  <DataTemplate>
    <Label ... BackgroundColor="{Binding BrandBackgroundColor}" ...

相关问题