MVVM-Light存在問題。我使用的版本5.3.0.0 ...MVVM-Light - RelayCommand CantExecute問題
.XAML
<DockPanel Dock="Top">
<Button Margin="5" VerticalAlignment="Top" HorizontalAlignment="Center" Command="{Binding CancelDownloadCommand}" FontSize="20"
Background="Transparent" BorderThickness="2" BorderBrush="{StaticResource AccentColorBrush4}" ToolTip="Cancelar"
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="Descargar"
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>
DownloadViewModel.cs
我用一個MessageBox,但對我來說,調用讀取方法XML。此示例不起作用,按鈕被禁用,但在執行結束時不會重新激活。我需要點擊用戶界面才能激活。
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
private async void Download()
{
Reset();
await Task.Run(() =>
{
MessageBox.Show("Hello");
});
Reset();
}
private void Reset()
{
IsEnabled = !IsEnabled;
IsEnabledCancel = !IsEnabledCancel;
}
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
{
if (_isEnabled != value)
{
_isEnabled = value;
RaisePropertyChanged();
}
}
}
private bool _isEnabledCancel;
private bool IsEnabledCancel
{
get { return _isEnabledCancel; }
set
{
if (_isEnabledCancel != value)
{
_isEnabledCancel = value;
RaisePropertyChanged();
}
}
}
通過使用CommandManager.InvalidateRequerySuggested(),我固定它。但是讀一些不推薦的地方,因爲這個命令會檢查所有的RelayCommand。這在我之前沒有發生過。
但是如果在Task.Run內沒有添加任何東西。它完美的作品。按鈕被激活並再次禁用。
private async void Download()
{
Reset();
await Task.Run(() =>
{
// WIDTHOUT CODE
// WIDTHOUT CODE
// WIDTHOUT CODE
});
Reset();
}