我有以下问题。我已将 DelegateCommand 从 ViewModel 移至单独的类。并观察 ViewModel 中的一个属性。到目前为止有效。
然后 CanExecute 将在视图初始化时调用第一个 NULL 。这也是正确的。然后第一次调用 OnNavigatedTo 并设置 TestModel。但是 CanExecute 再次使用 NULL 调用,这是错误的。如果第二次调用 OnNavigatedTo 并设置了 TestModel,则该值将正确传递给 CanExecute 方法。
命令类:
public class CommandFactory : BindableBase, ICommandFactory
{
#region Fields
private ICommand buttonTestCommandLocal;
#endregion
#region Properties
public ICommand ButtonTestCommand
{
get { return buttonTestCommandLocal ?? (buttonTestCommandLocal = new DelegateCommand<ITestModel>(ButtonTestCommand_Executed, ButtonTestCommand_CanExecute)); }
}
#endregion
#region Methods
private bool ButtonTestCommand_CanExecute(ITestModel parameter)
{
return parameter != null;
}
private void ButtonTestCommand_Executed(ITestModel parameter)
{
int x = 30;
Console.WriteLine(x.ToString());
}
#endregion
}
public interface ICommandFactory
{
ICommand ButtonTestCommand { get; }
}
视图模型:
public class ButtonRegionViewModel : BindableBase, INavigationAware
{
#region Fields
private ITestModel testModelLocal;
#endregion
#region Constructors and destructors
public ButtonRegionViewModel(ICommandFactory commandFactory)
{
CommandFactory = commandFactory;
//Does not work
if(commandFactory.ButtonTestCommand is DelegateCommand<ITestModel> buttonTestCommand)
buttonTestCommand.ObservesProperty(()=> TestModel);
}
#endregion
#region Properties
public ITestModel TestModel
{
get => testModelLocal;
private set
{
SetProperty(ref testModelLocal, value);
//Does work
//if (CommandFactory.ButtonCommand is IModelCommand modelCommand)
// modelCommand.RaiseCanExecuteChanged();
}
}
#endregion
#region Methods
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
if (!(navigationContext.Parameters["Element"] is ITestModel testModel))
return;
TestModel = testModel;
}
#endregion
}
看法:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="1" Margin="2" Padding="0" HorizontalAlignment="Center" HorizontalContentAlignment="Center"
CommandParameter="{Binding Path=TestModel, Mode=OneWay}" Content="CommandFactory.ButtonTestCommand"
Command="{Binding Path=CommandFactory.ButtonTestCommand}" Width="200" Height="100"/>
</Grid>
我不知道为什么这第一次不起作用。由于 RaiseCanExecuteChanged 直接工作。
感谢你的帮助 :-)