I have the following problem. I have moved the DelegateCommand from the ViewModel to a separate class. And observe a property in the ViewModel. That works so far.
Then CanExecute will call the first one with NULL when the view is initialized. Which is also correct. Then the first time OnNavigatedTo is called and the TestModel is set. But than CanExecute is called again with NULL which is wrong. If OnNavigatedTo is then called a second time and the TestModel is set, the value is passed correctly to CanExecute methode.
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
}
View:
<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>
I have no idea why this doesn't work the first time. Since RaiseCanExecuteChanged works directly.
Thanks for all your help :-)