【发布时间】:2016-06-21 14:20:25
【问题描述】:
我对 MVVM-Light 有疑问。我用的是5.3.0.0版本...
.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>
下载ViewModel.cs
我使用了 MessageBox,但在我的例子中,调用了一个读取 XML 的方法。此示例不起作用,按钮被禁用,但在执行结束时不会重新激活。我需要点击 UI 来激活。
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();
}
【问题讨论】:
标签: wpf mvvm-light