I'm making my first steps into using Commands (by implementing the ICommand interface) in my Windows Phone applications. Now I've run into a problem I can't seem to figure out. I'm binding a control, in this case it's a textbox, to the CommandParameter property of a Button:
<Button x:Name="BTN_Search"
Style="{StaticResource ButtonNoPressedStyle}"
BorderThickness="0"
ccontrols:TiltEffect.IsTiltEnabled="True"
Grid.Column="1"
Height="85"
Margin="0,0,0,-2"
CommandParameter="{Binding ElementName=TB_Search}"
Command="{Binding SearchTermCommand}">
<Button.Background>
<ImageBrush ImageSource="/Assets/Images/searchbtn.png" />
</Button.Background>
</Button>
When the application starts and the viewmodel is instantiated, the CanExecute method gets fired twice in a row.
public override bool CanExecute(object parameter)
{
if (parameter != null)
{
var textbox = parameter as TextBox;
if ((textbox.DataContext as MainPageViewmodel).SearchTerm == null)
{
(textbox.DataContext as MainPageViewmodel).SearchTerm = "";
return true;
}
else if (String.IsNullOrWhiteSpace(textbox.Text)) return false;
else if (textbox.Text.Any(Char.IsDigit)) return false;
else if (textbox.Text.Length < 4) return false;
else if (_commandExecuting) return false;
else
{
var bindingExpression = textbox.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();
return true;
}
}
return true;
}
The first time the parameter is null and the second time it contains the textbox. Because of this behavior I have to make it so that these first two times, the CanExecute method returns true, else the button will be disabled.
I've read some other topics that it may have to do with RaiseCanExecuteChanged(), but I'm not so sure of that either.
This question
has some answers regarding this issue, but the answers don't fit my needs, since most solutions are for WPF (using the CommandManager, or a IMultiValueConverter) and others don't seem to work.
Is there any solution to make sure CanExecute only fires once, or what's the explanation for this behavior?