单独的类中的DelegateCommand首次调用CanExecute参数为null

时间:2018-07-05 09:24:42

标签: c# wpf prism prism-6 delegatecommand

我有以下问题。我已经将DelegateCommand从ViewModel移到了单独的类。并观察ViewModel中的一个属性。到目前为止有效。

然后,初始化视图时,CanExecute将使用NULL调用第一个。这也是正确的。然后第一次调用OnNavigatedTo并设置TestModel。但是比CanExecute再次用NULL调用是错误的。如果第二次调用OnNavigatedTo并设置了TestModel,则该值将正确传递给CanExecute方法。

CommandClass:

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; }
}

ViewModel:

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可直接工作。

感谢您的帮助:-)

0 个答案:

没有答案