Xamarin forms iOS CollectionView steals focus after ItemsSource property is changed - xamarin.forms

I have a page with a collection view and a search bar that filters its contents.
I want the filtering to happen as the user types in the search bar, so I bind the TextChanged event of the SearchBar to a command in the view model, like so
var eventToCommandBehavior = new EventToCommandBehavior()
{
EventName = nameof(searchBar.TextChanged),
};
eventToCommandBehavior.SetBinding(EventToCommandBehavior.CommandProperty, nameof(MyViewModel.StartOrResetSearchTimerCommand));
searchBar.Behaviors.Add(eventToCommandBehavior);
In the view model:
public ICommand StartOrResetSearchTimerCommand => new Command(() =>
{
StartOrResetSearchTimer();
});
private void StartOrResetSearchTimer()
{
if (!timerStarted)
{
searchTimer = new Timer(_ => PerformSearch(), null, searchTimeout, searchTimeout);
timerStarted = true;
}
else
ResetTimer();
}
private void PerformSearch()
{
//my code
OnPropertyChanged(collectionViewItemsSourceBinding);
}
The StartOrResetSearchTimerCommand filters the ItemsSource binding, and calls OnPropertyChanged(itemsSourceBinding) to update the UI.
On Android and UWP everything works as expected. However on iOS, when OnPropertyChanged is called, the focus moves out of the search bar, resulting to the soft keyboard being closed after each keyboard input.
Has anyone else encountered this? Any suggestions?
I have already tried not using this approach, and only filter the ItemsSource when the search button is pressed, which works, when there is something to search for (ie, there is some input in the search bar)
When the search bar text is empty (ie after Backspace) then the search button is greyed out.
Update
For now, I am using this workaround:
Perfom the search only when the search button is pressed, and on TextChanged, check if the text is empty and reset the ItemsSourceworka

TextChanged is called anytime the text in the query box is changed. You can use this event to update your ItemsSource when the Text of the searchbar changes. You can refer to this part of the official example. First, given your ItemsSource, when you enter text in the searchbar, call the OnTextChanged event to update your ItemsSource, so that the real-time search keyboard will not lose focus.

Related

DispatchKeyEvent stops firing after Xamarin Forms Entry control IsFocused

I am building a Xamarin Forms mobile app that runs in Android on a Zebra scanner. I flip 2 different StackLayouts to IsVisble true/false to display different stuff in the UI. (StackLayout1 and StackLayout2)
The customer wants the user to be able to use the app entirely from the hardware keyboard on the scanner. So I have used the device Settings so that it never displays the virtual keyboard (I don’t think that matters for the issue I am having.)
I am overriding DispatchKeyEvent in a PageRenderer in the Android project and everything is working great … except.
The problem case:
StackLayout1 is displayed
the user taps an Entry control, putting the focus there
the user taps a button in the UI
the app displays StackLayout2
at this point the DispatchKeyEvent never fires no matter what key I press on the device keyboard
If an Entry box does NOT get the focus (step #2 above) the DispatchKeyEvent always fires in StackLayout2 and the StackLayouts display as expected.
If I programatically put the focus in an Entry box in StackLayout2 at step #3 above the DispatchKeyEvent fires fine.
That is not an OK solution. I have tried to progamatically put the focus on StackLayout2, and that code seems to do what is expected but DispatchKeyEvent does not fire.
Maybe I need to do something in the Android-project PageRenderer so that it is aware of StackLayout2 when it is made IsVisible = true.
Update 2: I found that I did NOT need custom StackLayouts. The solution which I posted below does not include any of this stuff I am describing in Update 1 (sorry, if that's confusing).
Update 1:
I added a ViewRenderer for both StackLayouts, and the code is hitting the OnElementChanged event when StackLayout2's IsVisible property flips to true, just great. Although the problem case is the same: DispatchKeyEvent does not fire once StackLayout2 is displayed, if an EntryBox had the focus in StackLayout1
Here is the OnElementChanged part of the new StackLayout ViewRenders
async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsVisible":
if (Element.IsVisible)
{
if (sender is StackLayout)
{
this.FocusableViewAvailable(this); // if I comment these 2 lines out I get the same bad result
this.Focusable = true; // if I comment these 2 lines out I get the same bad result
this.FocusableInTouchMode = true;
var dd = this.RequestFocus(); // this is always false
var ee = this.IsFocused; // this is always false
}
}
break;
}
}
Also, as I am pointing out in the comments ^ there, IsFocused is always false.
Ideas?
My hunch, "Maybe I need to do something in the Android project PageRenderer" was correct. In the DispatchKeyEvent I had to make the MainPage have the focus when the keypress was handled.
Here is what the DispatchKeyEvent looks like now (notice the comments):
public override bool DispatchKeyEvent(KeyEvent ke)
{
// MainPage.ReceiveKeyPress(e); is the method that this method returns to
bool KeyPressWasHandled = false;
KeyPressWasHandled = (Element as MainPage).ReceiveKeyPress(ke);
if (KeyPressWasHandled)
{
// this next block seems to be needed so that this class
// continues to receive the keypress event after an Entry box has had the focus
this.Focusable = true;
this.FocusableInTouchMode = true;
this.RequestFocus();
return true; // returning true tells the parent class that the keypress has been handled
} else
{
try
{
return base.DispatchKeyEvent(ke);
}
Now the "problem case" in my initial post is no longer a problem.
NOTE: I found that I did NOT need the custom ViewRenderers that I had made for the StackLayouts.

Xamarin.Forms.EntryCell: How to trigger the event while input any key

I have a problem with Xamarin.Forms.EntryCell. I want to know how to trigger an event if the text of the EntryCell has changed. Not the event 'Completed', it is just triggered when I press Enter after inputting anything.
<EntryCell
Label="User Id"
x:Name="UserIdEntryCell"
HorizontalTextAlignment="End"
Completed="UserIdCompleted"/>
Obviously there is no event that is fired when the text is changed (see the docs). Anyway, this does not mean that you can't achieve what you want, by means of Text property. Since you are using the event I do not assume that you use MVVM (you should really give it a try, though), hence we'll have to create a property we will bind the EntryCell.Text to in your view (I'm assuming a view, but for a page it would be quite similar)
In your code behind add a property Text that calls HandleTextChanged from its setter:
class MyView : ContentView
{
string _text;
public string Text
{
get => _text;
set
{
_text = value;
HandleTextChanged();
}
}
private void HandleTextChange()
{
// do whatever you need to do
}
}
You can bind this property to EntryCell.Text from your XAML
Now MyView.Text will be set every time the text in your EntryCell changes.

How do I create a JavaFX Alert with a check box for "Do not ask again"?

I would like to use the standard JavaFX Alert class for a confirmation dialog that includes a check box for "Do not ask again". Is this possible, or do I have to create a custom Dialog from scratch?
I tried using the DialogPane.setExpandableContent() method, but that's not really what I want - this adds a Hide/Show button in the button bar, and the check box appears in the main body of the dialog, whereas I want the check box to appear in the button bar.
Yes, it is possible, with a little bit of work. You can override DialogPane.createDetailsButton() to return any node you want in place of the Hide/Show button. The trick is that you need to reconstruct the Alert after that, because you will have got rid of the standard contents created by the Alert. You also need to fool the DialogPane into thinking there is expanded content so that it shows your checkbox. Here's an example of a factory method to create an Alert with an opt-out check box. The text and action of the check box are customizable.
public static Alert createAlertWithOptOut(AlertType type, String title, String headerText,
String message, String optOutMessage, Consumer<Boolean> optOutAction,
ButtonType... buttonTypes) {
Alert alert = new Alert(type);
// Need to force the alert to layout in order to grab the graphic,
// as we are replacing the dialog pane with a custom pane
alert.getDialogPane().applyCss();
Node graphic = alert.getDialogPane().getGraphic();
// Create a new dialog pane that has a checkbox instead of the hide/show details button
// Use the supplied callback for the action of the checkbox
alert.setDialogPane(new DialogPane() {
#Override
protected Node createDetailsButton() {
CheckBox optOut = new CheckBox();
optOut.setText(optOutMessage);
optOut.setOnAction(e -> optOutAction.accept(optOut.isSelected()));
return optOut;
}
});
alert.getDialogPane().getButtonTypes().addAll(buttonTypes);
alert.getDialogPane().setContentText(message);
// Fool the dialog into thinking there is some expandable content
// a Group won't take up any space if it has no children
alert.getDialogPane().setExpandableContent(new Group());
alert.getDialogPane().setExpanded(true);
// Reset the dialog graphic using the default style
alert.getDialogPane().setGraphic(graphic);
alert.setTitle(title);
alert.setHeaderText(headerText);
return alert;
}
And here is an example of the factory method being used, where prefs is some preference store that saves the user's choice
Alert alert = createAlertWithOptOut(AlertType.CONFIRMATION, "Exit", null,
"Are you sure you wish to exit?", "Do not ask again",
param -> prefs.put(KEY_AUTO_EXIT, param ? "Always" : "Never"), ButtonType.YES, ButtonType.NO);
if (alert.showAndWait().filter(t -> t == ButtonType.YES).isPresent()) {
System.exit();
}
And here's what the dialog looks like:

Flex extending ComboBox

I created a class CustomCombo.as that extends ComboBox. What is happening is that the CustomCombo combobox is showing as being editable. I do not want this and I cant find the properties to set the editable to false.
I also tried setting the combobox's textInput.editable control to false, but to no avail.
Any help would be greatly appreciated.
CustomCombo.as
package custom {
import spark.components.ComboBox;
public class CustomCombo extends ComboBox {
public function CustomCombo() {
super();
// this.editable = false; //<-- THIS DOESNT WORK ***Access of possibly undefined property editable through a reference with static type custom:CustomCombo
// this.textInput.editable = false; //<-- THIS DOESNT WORK ***Cannot access a property or method of a null object reference
}
}
}
After rummaging through the Flex 4 API I found that they suggest to use the DropDownList control. From what I can see is that they removed the editable property from the ComboBox control in Flex 4, but I may be wrong.
I implemented DropDownList and that solved my problem.
I see that you're using spark and not mx. The editable property I referred to is applicable only to mx based list. In spark, ComboBox extends DropDownListBase and is editable by default.
The ComboBox control is a child class of the DropDownListBase control. Like the DropDownListBase control, when the user selects an item from the drop-down list in the ComboBox control, the data item appears in the prompt area of the control.
One difference between the controls is that the prompt area of the ComboBox control is implemented by using the TextInput control, instead of the Label control for the DropDownList control. Therefore, a user can edit the prompt area of the control to enter a value that is not one of the predefined options.
For example, the DropDownList control only lets the user select from a list of predefined items in the control. The ComboBox control lets the user either select a predefined item, or enter a new item into the prompt area. Your application can recognize that a new item has been entered and, optionally, add it to the list of items in the control.
The ComboBox control also searches the item list as the user enters characters into the prompt area. As the user enters characters, the drop-down area of the control opens. It then and scrolls to and highlights the closest match in the item list.
So ideally, you should be using DropDownList in this case.
You're getting null error when trying to access textInput from the constructor because it hasn't been created yet. In mx based controls (Flex-3), you can access it from the creationComplete handler; I'm not quite sure how to do it for spark based controls.
Update: I think I've figured out how to access skin parts in spark (though you might wanna use the DropDownBox instead). You have to override the partAdded method.
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == textInput)
{
textInput.editable = false;
}
}
There's one catch though: it may not work in this case. The source code of ComboBox.as says that
the API ignores the visual editable and selectable properties
So DropDownList it is!
Initial answer, posted for mx ComboBox.
This shouldn't happen as the default value of the editable property is false.
Try explicitly setting the value to false from the constructor.
public function CustomCombo() {
super();
this.editable = false;
}

How to disable delete button in ASP.NET Dynamic Data?

I need to disable delete button GLOBALLY based on some condition?
The following solutions will not work for me:
http://csharpbits.notaclue.net/2009/07/securing-dynamic-data-preview-4-refresh.html
http://csharpbits.notaclue.net/2008/05/dynamicdata-miscellaneous-bits-part-6.html
Again, I do not want to go into every list and detail page and disable it there.
Why not just extend/inherit from button. You could make your own button that "knows" how to check if it should be hidden:
public class MyButton : Button
{
public void HiddenCheck()
{
bool visible = true;
//Check to see if the button should be hidden
this.Visible = visible;
}
}
Then, just use this button instead of the "System.Web.UI.WebControls.Button" button wherever you need the delete button functionality.
-Make that "Enabled." I read the post again, and I guess you aren't trying to "hide" the button, but disable it. The idea is the same though.

Resources