How to pass parameters to an ICommand? - c#

I defined an ICommand-Class ReadPersons which reads all person objects from the database with a particular where-clause.
The command is being executed trough pressing a button and the where-clause is being insert in a textbox.
Question: How can i pass the text from the textbox to the Execute-Command?
MainWindow.xaml:
<Button Command="{Binding ReadPersons}">Read persons</Button>
<TextBox Name="textBoxWhereClause" />
ReadPersons.cs:
public void Execute(object parameter)
{
// Read all persons with my where-clause
string whereClause = ??? //todo
}

Yes you can.
<Button Command="{Binding ReadPersons}"
CommandParameter="{Binding Text, ElementName=textBoxWhereClause}">
Read persons</Button>

<Button Command="{Binding ReadPersons}" CommandParameter="{Binding SomeProperty}" Content="Read Persons"/>

Related

Binding Text Change Event to prevent invalid input WPF XAML

I am currently trying to prevent a user from inputting anything aside from numbers into a textbox.
I currently have a Textbox with a textchange event which calls a relay command. however I am not able to effect the textbox from the relay command.
I have tried directly settings the textbox.text and that has not worked, nor has trying to return the string.
Here is my code
XAML
<TextBox x:Name="TextBox" Margin="5,5,0,0" Grid.Column="1" Grid.Row="3" HorizontalAlignment="Left" Width="31" ">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<command:EventToCommand Command="{Binding TextBoxTextChanged,Mode=TwoWay}"
CommandParameter="{Binding Path=Text, ElementName=TextBox}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
View Model
DaysBackTextChanged = new RelayCommand<string>(daysBackText =>
{
Func<string> function = () =>
{
if (!Regex.IsMatch(daysBackText, "[^0-9]+"))
{
//return TextBox.Text;
return "X";
}
else
{
return "Y";
}
};
});
Modify your XAML to add a PreviewTextInput event in the TextBox
PreviewTextInput="NumbersOnly"
Now,let's use Regex,shall we ?
using System.Text.RegularExpressions;
private void NumbersOnly(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
Here e.Handeled is to prevent anything rather than numbers being typed.
Hope this works :)

Why does adding a double click command disable my datagrid?

I have this XAML code:
<DataGrid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<prism:InvokeCommandAction Command="{Binding AddedSelectedClaimsCommand}" TriggerParameterPath="AddedItems" />
<prism:InvokeCommandAction Command="{Binding RemovedSelectedClaimsCommand}" TriggerParameterPath="RemovedItems" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseDoubleClick">
<prism:InvokeCommandAction Command="{Binding ViewDetailsCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.ContextMenu>
<ContextMenu >
<MenuItem Header="View details" Command="{Binding ViewDetailsCommand}"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
It works fine without the MouseDoubleClick EventTrigger. But when I added in the double click ability, the data grid suddenly appeared greyed out and rows could no longer be selected. Why?
Your canExecuteMethod delegate must be returning false for some reason, review your ViewModel and make sure all bellow is in place for you:
In you command initialization make sure you set canExecuteMethod delegate as well as your command action:
ViewDetailsCommand = new DelegateCommand(ExecuteViewDetailsCommand,
CanExecuteViewDetailsCommand);
Then goes your logic that verify if preconditions are met to execute this command. At the end it will enable or disable the associated control(s) for this command.
private bool CanExecuteViewDetailsCommand() {
return null != SelectedDetail;
}
If command successfully passed preconditions tests, then it can safely execute its method:
private void ExecuteViewDetailsCommand()
{
NavigateTo("DetailView",SelectedDetail);
}
You should have SelectedDetail property in place too (read/write):
Detail selectedDetail;
public Detail SelectedDetail
{
get { return selectedDetail; }
set {
SetProperty(ref selectedDetail, value);
RaiseCanExecuteEvents();
}
}
Note above RaiseCanExecuteEvents method invokation, this is a convenience method where you can force related commands validations:
protected virtual void RaiseCanExecuteEvents()
{
ViewDetailsCommand.RaiseCanExecuteChanged();
}

Delay in getting text on text box textchanged event - Windows phone

I created a TextBox. I wrote a TextChanged event in view model. The problem is, when I type 'a' in the TextBox, in the TextChanged event, I am getting "". Then if I type next letter 'b', I am getting the previous result 'a' and If I type the next letter 'c', I am getting 'ab' as result. Why is one char delay in the TextChanged event?
Here is my XAML code:
<toolkit:PhoneTextBox Visibility="{Binding IsSearchBoxVisible,Converter={StaticResource BoolToVisibilityConverter}}" TextChanged="txtboxPhoneContacts_TextChanged" Grid.Row="2" Width="450" FontSize="28" Foreground="Black" x:Name="txtboxPhoneContacts" VerticalContentAlignment="Center" Background="LightGray" Hint="{Binding Localizedresources.SearchContactsText,Source={StaticResource LocalizedStrings}}" Text="{Binding PhoneContactSearchText,Mode=TwoWay,UpdateSourceTrigger=Explicit}" Style="{StaticResource SearchTextBoxStyle}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding PhoneBookTextBoxTextChanged}" CommandParameter="{Binding Text,ElementName=txtboxPhoneContacts,BindsDirectlyToSource=True}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
<i:Interaction.Behaviors>
<controls:UpdateOnTextChangedBehavior></controls:UpdateOnTextChangedBehavior>
</i:Interaction.Behaviors>
</toolkit:PhoneTextBox>
My ViewModel.cs
private void OnPhoneBookTextBoxTextChanged(Object obj)
{
if (obj != null)
{
String text = obj.ToString();
searchResults = new ObservableCollection<PhoneBookEntity>(
from item in PhoneContactsList
where item.PhoneContactName.Contains(text)
select item);
}
}
Any suggestions is highly appreciated.

How to avoid multiline TextBox Enter keypress is swallowed when using InputBindings?

I'm doing WPF MVVM and have the following XAML code:
<TextBox Grid.Row="1" Name="Console" MinWidth="500" HorizontalAlignment="Stretch" AcceptsReturn="True" CharacterCasing="Upper" TextWrapping="WrapWithOverflow" Cursor="IBeam">
<TextBox.InputBindings>
<KeyBinding Command="{Binding Path=MyCommand}" CommandParameter="{Binding Text, ElementName=Console}" Key="Enter"/>
</TextBox.InputBindings>
</TextBox>
When handling the Enter press in the ViewModel's command property (initialized in constructor with event handler added):
private readonly MyCommand myCommand;
public ICommand MyCommand
{
get
{
return myCommand;
}
}
private void OnCommand(object sender, MyCommandEventArgs e)
{
<do something>
}
The event handler is called allright, but the Enter keypress is never passed back to the TextBox and the newline is not added (the cursor stays on the same line).
Doesn't event bubbling ensure that the Enter keypress gets passed on to the TextBox?
Could you just add "\n" to your textbox' Text-value?
(Would have add that as a comment but I may not do that yet...)

The call is ambiguous between the following methods or properties - WPF

I have a WPF form that has some buttons to save user input, delete, and cancel. I was trying to add functionality such that whenever the user clicks the cancel button, there is a pop up a message. Instead it throws an exception in my controller:
"The call is ambiguous between the following methods or properties"
Here is my view:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,0,0,0">
<Button Name="DeleteButton" Command="{Binding DeleteCommand}" CommandParameter="{Binding Path=SelectedStory}" Cursor="Hand" Height="25" IsEnabled="{Binding CanDelete}" Margin="5 0 0 0">Delete</Button>
<Button Name="SubmitButton" Command="{Binding SubmitCommand}" CommandParameter="{Binding Path=SelectedStory}" Cursor="Hand" Height="25" Margin="5 0 0 0">Submit</Button>
<Button Name="CancelButton" Command="{Binding CloseCommand}" CommandParameter="{Binding Path=SelectedStory}" Cursor="Hand" Height="25" Margin="5 0 0 0" >Cancel</Button>
</StackPanel>
My controller code:
public MetadataController(IGatewayService gateway, IEventAggregator eventAggregator, IDialogService dialog)
{
this.gateway = gateway;
this.eventAggregator = eventAggregator;
this.dialog = dialog;
// commands
this.CloseCommand = new DelegateCommand<StoryItem>(this.Close);//here i got the exception throwing "the call is ambiguous between the following methods or properties"
this.DeleteCommand = new DelegateCommand<StoryItem>(this.Delete);
this.SubmitCommand = new DelegateCommand<StoryItem>(this.Submit, this.HasFieldsRequiredBeforeSubmit);
this.eventAggregator.GetEvent<StorySelectedEvent>().Subscribe(OnStorySelected);
}
private void Close(StoryItem selsectedStory)//when i click my close button its not calling this method at all.
{
bool isConfirmed = this.dialog.ShowConfirmation("Are you sure you want to close?");
}
private void Delete(StoryItem selectedStory)
{
bool isConfirmed = this.dialog.ShowConfirmation("Are you sure you want to permanently delete ?");
if (isConfirmed)
{
this.gateway.DeleteStoryItem(selectedStory);
this.eventAggregator.GetEvent<CommandCompletedEvent>().Publish(CommandTypes.MetadataEntry);
}
}
The exception you're getting indicates that it doesn't how to access whatever method/property you're attempting to call. Perhaps there is some other method or property that is also called Close or CloseCommand and is causing the conflict?
The reason for the exception ,i do have the method already and i was trying to create one,that's why it throws that error.Thanks lot for the help guys.

Categories

Resources