How to set cursor positioned on focused Entry tag in XAML? - xaml

I tried using the CursorPosition value but it doesn't appear to be working. The value is a single digit and the cursor needs to update to be in front of the digit when the value is tapped (or focused upon). Anyone know what might be the issue here?
public PaymentOccurrencesControl()
{
InitializeComponent();
PaymentNumberEntry.Focused += PaymentEntryField_Focused;
}
private void PaymentEntryField_Focused(object sender, FocusEventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
PaymentNumberEntry.Focused += (s, e) =>
{
PaymentNumberEntry.CursorPosition = 1;
};
});
}

Wrap the code that sets CursorPosition in:
Device.BeginInvokeOnMainThread( () => {
…
});
This delays the cursor change until after xamarin and the phone’s OS have completed the focus action - which sets cursor position, overriding what you did.
ONLY wrap the line that sets cursor position:
public PaymentOccurrencesControl()
{
InitializeComponent();
PaymentNumberEntry.Focused += (s, e) =>
{
Device.BeginInvokeOnMainThread(() =>
{
PaymentNumberEntry.CursorPosition = 1;
};
});
}
Explanation: When the control gains focus, Android will begin executing your code after PaymentNumberEntry.Focused. It sees BeginInvoke, which tells Android "delay what's in here, until the current UI action (the control gaining focus) finishes". It queues this action:
() =>
{
PaymentNumberEntry.CursorPosition = 1;
};
This allows Android to do whatever it wants to CursorPosition (actually, to its native control's equivalent field). That's what makes the situation confusing - CursorPosition is not controlling the actual cursor position, until the next time it is given a value.
When it finishes, it returns to the MainThread loop, which looks for the next action to do. Which is your CursorPosition logic. Because your code runs last, it successfully updates Android's native cursor position.

Related

Gtk.DrawingArea mouse events using Vala

I have been trying to receive mouse events on my Gtk.DrawingArea, using Vala, with no success. Specifically I am sub-classing Gtk.DrawingArea and in my constructor I add the events I want to receive:
this.add_events (Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
Then, in the same constructor below, I register signal handlers for these events:
this.enter_notify_event.connect (
(page, event) => {
stdout.printf("mouse entered !!! \n");
return true;
}
);
this.button_press_event.connect (
(page, event) => {
stdout.printf("mouse click \n");
return false;
}
);
I tried both return true and return false to check what happens in both cases. However I see no messages on the console when I move the pointer on the Gtk.DrawingArea or when I click on it. I even set the events for the top Gtk.Window:
this.set_events (this.get_events() |
Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
but the events don't seem to get received. What could be going wrong?
Your code seems correct although it's not a MVCE. I would point out the callback handlers prototype as being incorrect but since you're not using event data it should not be a "problem". The callback prototypes for enter_notify_event and button_press_eventonly supply the event, so the page argument it's incorrect.
Anyway, i tested with a very simple and raw code and it worked. Please verify:
using Gtk;
public class MyWidget : Gtk.DrawingArea {
public MyWidget () {
this.set_events (Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
this.enter_notify_event.connect ((event) => {
stdout.printf ("mouse entered !!! \n");
return false;
});
this.button_press_event.connect ((event) => {
stdout.printf("mouse click \n");
return false;
});
}
}
public void main (string[] args) {
Gtk.init (ref args);
var window = new Gtk.Window ();
window.add (new MyWidget ());
window.destroy.connect (Gtk.main_quit);
window.show_all ();
Gtk.main ();
}
Compile with valac test.vala --pgk gtk+-3.0.
The result is:
Using Vala 0.30.2 and Gtk+ 3.18 on Fedora 23.

Real time GPS UWP

I really want to know how do I can update the position of the user in the map while the UWP app was running in bakground
Here is my code right now
private async void PinPoints()
{
//Pin point to the map
Windows.Devices.Geolocation.Geopoint position = await Library.Position();
double lat = position.Position.Latitude;
double lon = position.Position.Longitude;
//Geoposition alttest = await Library.Temp();
//alt = alttest.Coordinate.Altitude;
DependencyObject marker = Library.Marker(""
//+ Environment.NewLine + "Altitude " + alt
);
Display.Children.Add(marker);
Windows.UI.Xaml.Controls.Maps.MapControl.SetLocation(marker, position);
Windows.UI.Xaml.Controls.Maps.MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 0.5));
Display.LandmarksVisible = true;
Display.ZoomLevel = 16;
Display.Center = position;
}
This function will pinpoint the current location for me but it will do only when user open this page due to I've put it in the public Map() {}
Current : Get the location when open map page and when I walk the map still be the same place
What I want : The position keep changing while I move on and also run on background (If application is close location data still changed)
Is there any code to solve this location problem if I have to add code where should I fix and what should I do?
Additional now I perform the background (Not sure is it work or not) by create the Window Runtime Component (Universal) with class like this
*I already put this project as the reference of the main one
namespace BackgroundRunning
{
public sealed class TaskBG : IBackgroundTask
{
BackgroundTaskDeferral _deferral = null;
Accelerometer _accelerometer = null;
Geolocator _locator = new Geolocator();
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
try
{
// force gps quality readings
_locator.DesiredAccuracy = PositionAccuracy.High;
taskInstance.Canceled += taskInstance_Canceled;
_accelerometer = Windows.Devices.Sensors.Accelerometer.GetDefault();
_accelerometer.ReportInterval = _accelerometer.MinimumReportInterval > 5000 ? _accelerometer.MinimumReportInterval : 5000;
_accelerometer.ReadingChanged += accelerometer_ReadingChanged;
}
catch (Exception ex)
{
// Add your chosen analytics here
System.Diagnostics.Debug.WriteLine(ex);
}
}
void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_deferral.Complete();
}
async void accelerometer_ReadingChanged(Windows.Devices.Sensors.Accelerometer sender, Windows.Devices.Sensors.AccelerometerReadingChangedEventArgs args)
{
try
{
if (_locator.LocationStatus != PositionStatus.Disabled)
{
try
{
Geoposition pos = await _locator.GetGeopositionAsync();
}
catch (Exception ex)
{
if (ex.HResult != unchecked((int)0x800705b4))
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
public void Dispose()
{
if (_accelerometer != null)
{
_accelerometer.ReadingChanged -= accelerometer_ReadingChanged;
_accelerometer.ReportInterval = 0;
}
}
}
}
Your Solution :
Make 3 projects in your solution.
1> Background Task "references App_Code"
2> App_Code "contains calculations,mostly Backend Code"
3> Map(Main Project) "references App_Code"
Register a background Task to your project and specify the time interval after which it should run again
Scenario 1> App Open,User Requests Update
Trigger Your background Task from code behind.
Scenario 2> App Closed,Not Being Used
Run your background task!
So basically keep your backgroundTask simple(make it a class in whose run method you just call the proper App_Code Classes Method) and all calculations that you want to happen in the background keep them in App_Code. Also, if I am no wrong the minimum interval between which a background Task is triggered by itself cannot be set below 15 minutes.
For real-time you could look at SignalR ( can't help any further here)

XAML: Tap a textbox to enable?

In XAML and WinRT, Is there a way to set up a textbox so that it is disabled for text input until it is tapped.
I tried setting up the Tapped event and then setting the IsEnabled=true, but that only seems to work if the IsEnabled=true in the first place.
I found this on MSDN:
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/708c0949-8b06-40ec-85fd-201139ca8b2d
Talks about adding the TappedEvent manually to the event handled for each TextBox, which is cumbersome, but also doesn't seem to work unless IsEnabled was already set to true.
Basically, I want a form where all textboxes display data but are disabled unless the user taps to enable the box and then type.
You can use IsReadOnly instead of IsEnabled to achieve what you are looking for. In addition, you can set up the tapped event handlers in code easily. I'm not sure if setting up handlers in code is a requirement for this to work, as you noted above; however, it does simplify things.
Here are the details.
In the constructor of your page class (here it is MainPage), call the setup function:
public MainPage()
{
this.InitializeComponent();
// call the setup for the textboxes
SetupTextBoxes();
}
Here is where we do the magic - make all textboxes on this page readonly and set up tap handler:
private void SetupTextBoxes()
{
var tbs = GetVisualChildren<TextBox>(this, true);
foreach (var tb in tbs)
{
tb.IsReadOnly = true;
tb.AddHandler(TappedEvent, new TappedEventHandler(tb_Tapped), true);
}
}
Utility function to get a list of all children of the given type (T) of the passed in parent.
private List<T> GetVisualChildren<T>(DependencyObject parent, bool recurse = true)
where T : DependencyObject
{
var children = new List<T>();
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
var child = v as T;
if (child == null && recurse)
{
var myChildren = GetVisualChildren<T>(v, recurse);
children.AddRange(myChildren);
}
if (child != null)
children.Add(child);
}
return children;
}
Finally, the event handler. This enables each textbox when tapped.
private void tb_Tapped(object sender, TappedRoutedEventArgs e)
{
((TextBox)(sender)).IsReadOnly = false;
}

how to properly detect which mouse buttons are down in JavaFX

I've set a listener to my Pane so that it will detect mouse left and right buttons being down.
But when I hold left mouse button, then press right one, previous action seem to lose it's effect!
My code:
root.setOnMouseDragged(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent t) {
if(t.getButton() == MouseButton.PRIMARY) f1();
if(t.getButton() == MouseButton.SECONDARY) f2();
}
});
while holding LMB I have f1() running, but when I push RMB it seems like new event totally overwrites previous one: only f2() runs.
How can I separate this two events?
getButton() can return only one value at a time. And it's latest pressed button. If you need to detect multiple mouse down being pressed you need to use corresponding functions:
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (t.isPrimaryButtonDown()) {
System.out.println("rockets armed");
}
if (t.isSecondaryButtonDown()) {
System.out.println("autoaim engaged");
}
}
});

Race condition in Rhino DSL?

In my current project I am working with Boo/Rhino DSL (what a great thing(s) by the way).
In digging in the code I came across the following piece of code:
engine.Cache.WriteLock( () =>
{
engine.Storage.NotifyOnChange(urls, delegate(string invalidatedUrl)
{
engine.Cache.Remove(invalidatedUrl);
if (!standAloneCompilation.Contains(invalidatedUrl))
standAloneCompilation.Add(invalidatedUrl);
});
});
the intention here is pretty clear: the engine.Cache has to be protected from race condition when a url is removed from it. The problem I see here is that what is really protected is a call to the Storage.NotifyOnChange - not the Cache.Remove.
And all NotifyOnChange does is taking the supplied delegate and attach it as an event handler to the 'FileWatcher' it creates. So instead of protecting the Cache.Remove the write lock here protects creating the the FileWatcher, and leaves the Cache.Remove unprotected.
I have great respect to both Boo and Rhino, which makes me wonder - am missing something here? or the write lock should be really moved inside the delegate?
Here is the NotifyOnChange code if you are wondering:
public virtual void NotifyOnChange(IEnumerable<string> urls, Action<string> action)
{
lock (pathToFileWatchers)
{
string[] commonPaths = GatherCommonPaths(urls);
foreach (string path in commonPaths)
{
FileSystemWatcher watcher;
if(pathToFileWatchers.TryGetValue(path, out watcher)==false)
{
pathToFileWatchers[path] = watcher = new FileSystemWatcher(path, FileNameFormat);
watcher.EnableRaisingEvents = true;
}
watcher.Changed += delegate(object sender, FileSystemEventArgs e)
{
action(e.FullPath);
};
}
}
}