【发布时间】:2010-09-20 20:16:24
【问题描述】:
我无法让RelayCommand 正确启用/禁用附加的控件。
我在按钮上附加了一个 EventToCommand 元素。该命令数据绑定到 ViewModel。最初,该按钮被禁用(预期行为),但我似乎无法获得 CanExecute 逻辑来检查它的值。当CurrentConfigFile 设置并存在时,应启用该按钮。我已经执行了代码并在调试中检查了文件的值以确保它已设置,但控件仍然被禁用。我试过CommandManager.InvalidateRequerySuggested() 和command.RaiseCanExecuteChanged(),但它不会启用。
我想知道 lambdas 是否不能正常工作于 CanExecute 行为(即使示例使用了它们),或者 CanExecute 行为需要数据绑定到另一个元素。
这是我的代码:
// The FileInfo being checked for existence before the button should be enabled
public const string CurrentConfigFilePN = "CurrentConfigFile";
public FileInfo CurrentConfigFile
{
get
{
return _currentConfigFile;
}
set
{
if (_currentConfigFile == value)
{
return;
}
var oldValue = _currentConfigFile;
_currentConfigFile = value;
// Update bindings, no broadcast
RaisePropertyChanged(CurrentConfigFilePN);
}
}
public MainViewModel()
{
// snip //
SaveCommand = new RelayCommand(SaveConfiguration,
() => CurrentConfigFile != null && CurrentConfigFile.Exists);
}
private void SaveConfiguration()
{
// export model information to xml document
ExportXMLConfiguration(CurrentConfigFile);
}
和标记
<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<GalaSoft:EventToCommand x:Name="SaveETC"
Command="{Binding SaveCommand}"
MustToggleIsEnabledValue="true" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
更新:
根据 Isak Savo 的建议,我将 RelayCommand 直接绑定到按钮上
<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5"
Command="{Binding SaveCommand}"/>
当设置FileInfo 时,它开始禁用并正确启用。猜猜我应该记住不要修复没有损坏的东西!
【问题讨论】:
标签: c# wpf mvvm-light