有时UI不会更新,必须使用命令刷新命令。 (RelayCommand)。例如,启用或禁用按钮。 我在那里寻找如何解决问题,我找到了这个解决方案 CommandManager.InvalidateRequerySuggested()。 这有效,但我发现这个“CommandManager.InvalidateRequerySuggested()尝试验证所有命令,这完全无效(在你的情况下很慢) - 在每次更改时,你都要求每个命令重新检查它的CanExecute()” 我已经完成了一些应用程序(代码隐藏很像我遇到的问题)我有这个问题。 当方法执行结束时,按钮不会更新,我需要在UI上单击一次。
...
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
...
...
private ICommand _downloadCommand;
public ICommand DownloadCommand
{
get
{
return _downloadCommand ?? (_downloadCommand = new RelayCommand(Download, () => IsEnabled));
}
}
private ICommand _cancelDownloadCommand;
public ICommand CancelDownloadCommand
{
get
{
return _cancelDownloadCommand ?? (_cancelDownloadCommand = new RelayCommand(CancelDownload, () => IsEnabledCancel));
}
}
private bool _isEnabled = true;
private bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
RaisePropertyChanged();
}
}
private bool _isEnabledCancel;
private bool IsEnabledCancel
{
get { return _isEnabledCancel; }
set
{
_isEnabledCancel = value;
RaisePropertyChanged();
}
}
private async void Download()
{
IsEnabled = false;
IsEnabledCancel = true;
await Task.Run(() =>
{
...
...
...
...
...
});
IsEnabled = true;
IsEnabledCancel = false;
}
.XAML
<DockPanel Dock="Top">
<Button Margin="5" VerticalAlignment="Top" HorizontalAlignment="Center" Command="{Binding CancelDownloadCommand}" FontSize="20"
Background="Transparent" BorderThickness="2" BorderBrush="{StaticResource AccentColorBrush4}" ToolTip="Cancel"
DockPanel.Dock="Right">
<StackPanel Orientation="Horizontal">
<Image Source="Images/48x48/Error.png" Height="48" Width="48"/>
<Label Content="{Binding ToolTip, RelativeSource={RelativeSource AncestorType={x:Type Button}}}" FontFamily="Segoe UI Light"/>
</StackPanel>
</Button>
<Button Margin="5" VerticalAlignment="Top" HorizontalAlignment="Center" Command="{Binding DownloadCommand}" FontSize="20"
Background="Transparent" BorderThickness="2" BorderBrush="{StaticResource AccentColorBrush4}" ToolTip="Download"
DockPanel.Dock="Right">
<StackPanel Orientation="Horizontal">
<Image Source="Images/48x48/Download.png" Height="48" Width="48"/>
<Label Content="{Binding ToolTip, RelativeSource={RelativeSource AncestorType={x:Type Button}}}" FontFamily="Segoe UI Light"/>
</StackPanel>
</Button>
</DockPanel>