只显示从一个可观察集合到datagridview的可用字母



也许这是一个糟糕的设计想法,但这是我的想法:

public class NetworkDrive : BaseNotify
{
private char letter;
public char Letter
{
get => letter;
set => SetAndNotify(ref letter, value, nameof(Letter));
}
private string name;
public string Name
{
get => name;
set => SetAndNotify(ref name, value, nameof(Letter));
}
private bool isLetterAvailable;
public bool IsLetterAvailable
{
get => isLetterAvailable;
set => SetAndNotify(ref isLetterAvailable, value, nameof(Letter));
}
}
public class EditDriveViewModel : Screen
{
public ObservableCollection<NetworkDrive> NetworkDrives { get; } = new();
}

NetworkDrives被所有字母填充,当用户选择一个字母并命名它时,该字母不再可用,因此IsLetterAvailable设置为false。

我想在datagridview中列出它,但只有使用中的字母,即:字母与IsLetterAvailable设置为false,但如果我使用ItemsSource到NetworkDrives,它将列出一切。

如果我这样做:

public ObservableCollection<NetworkDrive> UsedNetworkDrives
{
get => NetworkDrives.Where(x => !x.IsLetterAvailable).ToList();
}

然后我就失去了通知,也就失去了将字母设置为真/假并反映出来的能力。

在datagridview中,我也有一个字母组合框,以便用户可以更改它,所以我还需要管理它,以便使用的字母显示为红色,如果选择,用户不能使用。

有办法解决这个问题吗?

如果您不想触摸视图模型中的源集合,您可以在视图中使用过滤的CollectionViewSource:

<Window.Resources>
<CollectionViewSource x:Key="cvs" Source="{Binding NetworkDrives}"
Filter="CollectionViewSource_Filter"
IsLiveFilteringRequested="True"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<CollectionViewSource.LiveFilteringProperties>
<s:String>IsLetterAvailable</s:String>
</CollectionViewSource.LiveFilteringProperties>
</CollectionViewSource>
</Window.Resources>
...
<ComboBox x:Name="cmb"
ItemsSource="{Binding Source={StaticResource cvs}}"
DisplayMemberPath="Name" />

private void CollectionViewSource_Filter(object sender, FilterEventArgs e) =>
e.Accepted = e.Item is NetworkDrive networkDrive
&& networkDrive.IsLetterAvailable;