我在 .NET MAUI 应用程序中添加了一个“附加图像”按钮,该按钮运行良好。在旁边,我添加了一个删除按钮和一个选择器,用于描述先前选择的图像的文件名:
<!-- Attach Image Button -->
<Button MaximumWidthRequest="150"
Text="Attach images"
TextColor="{StaticResource SnowWhite}"
BackgroundColor="{StaticResource AlpineBlue}"
CornerRadius="25"
Command="{Binding AttachImagesCommand}">
<Button.ImageSource>
<FontImageSource FontFamily="MSO"
Glyph="{x:Static helpers:IconFont.Attach_file_add}"
Size="20"
Color="{StaticResource NightBlue}" />
</Button.ImageSource>
</Button>
<!-- Delete Attached Image Button -->
<Button BackgroundColor="{StaticResource SnowWhite}"
Command="{Binding RemoveImageCommand}"
IsVisible="{Binding Images, Converter={StaticResource IsListNotNullOrEmptyConverter}}">
<Button.ImageSource>
<FontImageSource FontFamily="MSO"
Glyph="{x:Static helpers:IconFont.Delete}"
Size="20"
Color="{StaticResource NightBlue}" />
</Button.ImageSource>
</Button>
<!-- Images Picker -->
<Picker
ItemsSource="{Binding Images}"
ItemDisplayBinding="{Binding FileName}"
SelectedItem="{Binding CurrentImage, Mode=TwoWay}"
SelectedIndex="{Binding CurrentImageIndex, Mode=TwoWay}"
IsVisible="{Binding Images, Converter={StaticResource IsListNotNullOrEmptyConverter}}"
/>
删除按钮似乎也工作正常,因为它从附加的 ObservableCollection 中删除 ViewModel 中的 FileResult:
[ObservableProperty]
private FileResult _currentImage = null;
[ObservableProperty]
private int _currentImageIndex = 0;
[ObservableProperty]
private ObservableCollection<FileResult> _images = new();
// ...
[RelayCommand]
private async Task OnAttachImagesAsync()
{
var results = await FilePicker.PickMultipleAsync(new PickOptions
{
PickerTitle = "Pick Image(s) Please",
FileTypes = FilePickerFileType.Images
});
if (results == null)
return;
Images = new ObservableCollection<FileResult>(results);
CurrentImage = Images.First();
}
// ...
[RelayCommand]
private void OnRemoveImage()
{
Images.RemoveAt(CurrentImageIndex);
}
但是,如果 ObservableCollection 中的所有项目都已被删除,则这两个组件仍然可见:
为什么 .NET MAUI Community Toolkit 的转换器“IsListNullOrEmptyConverter”在视图开始时工作正常,但没有相应更新?Mode=TwoWay
我是否错过了XAML 或NotifyCanExecuteChanged
C# 中的指令?
OnPropertyChanged()
正如 Julian 建议的那样,当您删除最后一项时,您需要手动调用: