我有两个 Gridview 来显示壁纸,一个用于图像壁纸,一个用于纯色壁纸。
现在我想用一个“WallpaperCollection”条件绑定两个Gridview(同时包含图片壁纸和纯色壁纸),IsSolidColor值将用于过滤出Gridview需要显示的壁纸,那么,如何进行这个条件绑定呢?
图像壁纸的GridView:
<GridView Name="ImageWallpapers"
ItemsSource="{x:Bind ViewModel.ImageWallPaperCollection, Mode=OneWay}"
IsItemClickEnabled="True"
FlowDirection="LeftToRight"
SelectionMode="Single"
IsMultiSelectCheckBoxEnabled="False"
ItemClick="ImageWallpaperCollection_ItemClick"
Padding="5,0,5,0">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate x:DataType="Models:Wallpaper">
<Image Source="{x:Bind ImagePath, Mode=OneWay}" Height="100" Width="150" Margin="5,5,5,5"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
纯色壁纸的 GridView:
<GridView Name="SolidColorWallpaper"
ItemsSource="{x:Bind ViewModel.SolidColorWallpaerCollection, Mode=OneWay}"
IsItemClickEnabled="True"
FlowDirection="LeftToRight"
SelectionMode="Single"
IsMultiSelectCheckBoxEnabled="False"
ItemClick="SolidColorWallpaperCollection_ItemClick"
Padding="5,0,5,0">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate x:DataType="Models:Wallpaper">
<Rectangle Fill="{x:Bind Color}" Height="100" Width="150" Margin="5,5,5,5" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
壁纸:
public class Wallpaper
{
public string Color { get; set; }
public string ImagePath { get; set; }
public bool IsSolidColor { get; set; }
}
您应该尝试 CommunityToolkit.WinUI.Collections
NuGet 包中的
AdvancedCollectionView:
public class Wallpaper
{
public string Name { get; set; }
public bool IsSolidColor { get; set; }
}
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<Wallpaper> _wallpapers = new();
[ObservableProperty]
private AdvancedCollectionView _wallpapersView = new();
public MainViewModel()
{
Wallpapers.Add(new Wallpaper { Name = "Wallpaper 1", IsSolidColor = false });
Wallpapers.Add(new Wallpaper { Name = "Solid Color 4", IsSolidColor = true });
Wallpapers.Add(new Wallpaper { Name = "Wallpaper 3", IsSolidColor = false });
Wallpapers.Add(new Wallpaper { Name = "Solid Color 1", IsSolidColor = true });
Wallpapers.Add(new Wallpaper { Name = "Solid Color 2", IsSolidColor = true });
Wallpapers.Add(new Wallpaper { Name = "Solid Color 3", IsSolidColor = true });
Wallpapers.Add(new Wallpaper { Name = "Wallpaper 2", IsSolidColor = false });
Wallpapers.Add(new Wallpaper { Name = "Solid Color 5", IsSolidColor = true });
WallpapersView.Source = Wallpapers;
}
[RelayCommand]
private void SwitchFilter()
{
if (WallpapersView.Filter is null)
{
WallpapersView.Filter = item => item is Wallpaper { IsSolidColor: true };
}
else
{
WallpapersView = new AdvancedCollectionView(Wallpapers);
}
}
}
ObservableObject
和 ObservableProperty
来自 CommunityToolkit.Mvvm NuGet 包,但您可以在没有它们的情况下使用 AdvancedCollectionView
。