How to bind the 'Selected' property for a UIButton in MvvmCross - uibutton

I have a weird thing. On the Simulator iOS 10.3. the following code works just fine.
set.Bind(Circle1).For("Selected").To(vm => vm.PincodeCircles[0].Activated);
On my iPad Pro 12.9 I get an error saying the following:
[0:] MvxBind:Warning: 2.68 Failed to create target binding for binding Selected for PincodeCircles[0].Activated
I've already tried the following:
set.Bind(Circle1).For(button => button.Selected).To(vm => vm.PincodeCircles[0].Activated);
and gives the same error:
[0:] MvxBind:Warning: 4.27 Failed to create target binding for binding Selected for PincodeCircles[0].Activated
Activated is defined as follows on the viewmodel:
public bool Activated
{
get { return this._activated; }
set { this.SetProperty(ref this._activated, value); }
}
The Cirle1 button is of type UICircleButton. Here's the class:
using CoreGraphics;
using Foundation;
using System;
using UIKit;
namespace NN.Plugin.Utils.iOS
{
public partial class UICircleButton : UIButton
{
public UICircleButton(IntPtr handle) : base(handle)
{
Layer.BorderColor = UIColor.Black.CGColor;
Layer.BorderWidth = 2;
}
public nfloat BorderWidth
{ get
{
return Layer.BorderWidth;
}
set
{
Layer.BorderWidth = value;
}
}
public CGColor BorderColor
{
get
{
return Layer.BorderColor;
}
set
{
Layer.BorderColor = value;
}
}
public nfloat PointSize
{
get => Font.PointSize;
set => Font = Font.WithSize(value);
}
public override CGRect ContentRectForBounds(CGRect rect)
{
var newRect = base.ContentRectForBounds(rect);
Layer.CornerRadius = newRect.Width / 2;
return newRect;
}
}
}

Related

Getting could not create an native instance of the type 'JumioNetverifyBinding.NetverifyConfiguration' the native class hasn't been loaded exception

I am trying to bind Jumio Natverify library in Xamarin iOS project by creating Objective c library project.
I have crated ApiDefination.cs and Struct.cs file data using sharpie tool. But when I am trying on run it I am getting Could not create an native instance of the type 'JumioNetverifyBinding.NetverifyConfiguration': the native class hasn't been loaded. exception.
ApiDefinition class - ApiDefinition.cs
Struct class - Struct.cs
Called NetverifyViewController from iOS Binding project:
using Foundation;
using JumioNetverifyBinding;
using System;
using UIKit;
namespace JumioNetverifyDemo
{
public partial class ViewController : UIViewController
{
NetverifyViewController netverifyViewController;
public ViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
StartNetverifyButton.TouchUpInside += startNetverify;
}
public void CreateNetverifyController()
{
NetverifyConfiguration config = new NetverifyConfiguration();
config.ApiToken = "My_token_key";
config.ApiSecret = "Secrate_key";
config.DataCenter = JumioDataCenter.Eu;
config.Delegate = new NetverifyViewControllerDelegateHandler(this);
this.netverifyViewController = new NetverifyViewController(config);
}
public void startNetverify(object sender, EventArgs e)
{
this.CreateNetverifyController();
if (this.netverifyViewController != null)
{
this.PresentViewController(netverifyViewController, true, null);
}
else
{
Console.WriteLine("Netverify Mobile SDK : NetverifyViewController is null");
}
}
public void DisplayAlertAsync(string title = "Alert", string message = "")
{
var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(okAlertController, true, null);
}
public class NetverifyViewControllerDelegateHandler : NetverifyViewControllerDelegate
{
private ViewController _viewController;
public NetverifyViewControllerDelegateHandler(ViewController viewController)
{
_viewController = viewController;
}
public override void DidCancelWithError(NetverifyViewController netverifyViewController, NetverifyError error, string scanReference, string accountId)
{
Console.WriteLine("NetverifyViewController did finish initializing, error:" + error.Message);
_viewController.DisplayAlertAsync("Error : " + error.Message);
}
public override void DidFinishWithDocumentData(NetverifyViewController netverifyViewController, NetverifyDocumentData documentData, string scanReference, string accountId, bool authenticationResult)
{
_viewController.DisplayAlertAsync("Scan Reference : " + scanReference);
}
}
}
}
I am looking for anyway to handle this exception and make this library work, if anyone have idea about this? Any help would be appreciated.

Save and displaying high score with variable across classes unity

I need to get the variable score from my other class and set it as a UserPrefs key. it doesnt seem to be setting as i have a GUI label ingame which shos "None" if there is no UserPrefs key "Highscore".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class Player : MonoBehaviour {
public Vector2 jumpForce = new Vector2(0, 300);
private Rigidbody2D rb2d;
Generator SwagScript;
GameObject generator;
// Use this for initialization
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
generator = GameObject.FindGameObjectWithTag("Generator");
SwagScript = generator.GetComponent<Generator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp("space"))
{
rb2d.velocity = Vector2.zero;
rb2d.AddForce(jumpForce);
}
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
void Die()
{
if (PlayerPrefs.HasKey("HighScore"))
{
if (PlayerPrefs.GetInt("Highscore") < SwagScript.score)
{
PlayerPrefs.SetInt("HighScore", SwagScript.score);
}
else
{
PlayerPrefs.SetInt("HighScore", SwagScript.score);
}
}
Application.LoadLevel(Application.loadedLevel);
}
}
Unless you're creating the Highscore playerpref somewhere else, the Die() method won't never create it, since the if (PlayerPrefs.HasKey("HighScore")) will always return false.
Just remove that if.

Windows Store Apps: animate control when visibility changes?

In my app I have A grid with visibility bound to a property in the view model.
What I want to do is when the visibility property changes at the view model, the grid fades in or out according to the visibility value: Visible/Collapsed.
how can I achieve this ?
Inspired by the answer of "HDW Production", here's the code for Windows Store and Windows Phone Store apps:
public class FadingVisibilityGrid : Grid
{
public static readonly DependencyProperty DeferredVisibilityProperty = DependencyProperty.Register(
"DeferredVisibility", typeof (Visibility), typeof (FadingVisibilityGrid), new PropertyMetadata(default(Visibility), DeferredVisibilityChanged));
private static void DeferredVisibilityChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var newVisibility = (Visibility)e.NewValue;
var grid = (FadingVisibilityGrid)sender;
var animation = new DoubleAnimation
{
Duration = new Duration(TimeSpan.FromMilliseconds(200))
};
Storyboard.SetTarget(animation, grid);
Storyboard.SetTargetProperty(animation, "Grid.Opacity");
grid.FadeStoryBoard.Stop();
grid.FadeStoryBoard = new Storyboard();
grid.FadeStoryBoard.Children.Add(animation);
if (newVisibility == Visibility.Visible)
{
animation.From = 0;
animation.To = 1;
grid.Visibility = Visibility.Visible;
grid.FadeStoryBoard.Begin();
}
else
{
animation.From = 1;
animation.To = 0;
grid.FadeStoryBoard.Completed += (o, o1) =>
{
grid.Visibility = newVisibility;
};
grid.FadeStoryBoard.Begin();
}
}
public Visibility DeferredVisibility
{
get { return (Visibility) GetValue(DeferredVisibilityProperty); }
set { SetValue(DeferredVisibilityProperty, value); }
}
private Storyboard _fadeStoryBoard = new Storyboard();
public Storyboard FadeStoryBoard
{
get { return _fadeStoryBoard; }
set { _fadeStoryBoard = value; }
}
}
You need a new DependencyProperty, either by inheriting from Grid and adding one or by creating an attached property. Let's call it DeferredVisibility and let it be of type Visibility.
When DeferredVisibility is changed to Visible, set the Visibility to Visible and animate the opacity from 0 to 1.
When DeferredVisibility is changed to Collapsed, animate the opacity from 1 to 0 and THEN set the Visibility to Collapsed.

Custom control child controls not persisted to ViewState in ASP.NET 4.0

We just switched target framework in our ASP.NET web application from 3.5 to 4.0. We ran into the following problem:
We have a couple of custom controls that worked fine in 3.5 but now with 4.0 they are not persisted in ViewState, one of them is basically a wrapper for other controls that inherits the Label class and the aspx-code looks like this:
<fsc:FormLabel ID="l_purchaserNo" runat="server" CssClass="label" Text="Purchaser">
<asp:TextBox ID="tb_purchaserNo" runat="server" CssClass="textBox" MaxLength="50" />
</fsc:FormLabel>
and the resulting html is:
<span id="l_purchaserNo" class="label">
<label class="header" for="tb_purchaserNo">Purchaser</label>
<span class="valueContainer">
<input name="tb_purchaserNo" type="text" id="tb_purchaserNo" class="textBox" />
</span>
</span>
So the control basically just adds a few span-tags and a label that is connected to the textbox.
After postback the html-code in 4.0 was:
<span id="l_purchaserNo" class="label"></span>
i.e. everything within the outer wrapper was gone and anything entered in the textbox could not be retreived from code behind.
Below you find the code for our FormLabel class.
We found that by setting ViewStateMode=Disabled on our custom control fsc:FormLabel and ViewStateMode=Enabled on the asp:TextBox the inner controls where persisted to ViewState but at the same time we lost ViewState on the wrapper and since we translate the text on the wrapper label we need viewstate for this as well (actually we tried every combination and setting ViewStateMode=Enabled on fsc:FormLabel did not help, regardless of how we set the ViewStateMode on the page). EnableViewState is true on all levels.
Could someone tell us how to get ViewState to work as before in 3.5, on ALL controls - wrapper as well as wrapped controls?
Thanks
Christian, Zeljko, Jonas
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FormLabel
{
public class FormLabel : Label
{
private bool HasChildren
{
get
{
return Controls.Count > 0;
}
}
public override string Text
{
get
{
if (!HasChildren)
{
return base.Text;
}
var text = ViewState[ID + "Text"] as String;
if (text != null)
{
((LiteralControl)Controls[0]).Text = text;
}
return ((LiteralControl)Controls[0]).Text;
}
set
{
if (!HasChildren)
{
base.Text = value;
return;
}
((LiteralControl)Controls[0]).Text = value;
}
}
public void SetText(string text)
{
((LiteralControl)Controls[0]).Text = text;
ViewState[ID + "Text"] = text;
}
public bool IndicateRequired
{
get
{
object state = ViewState[String.Format("{0}_IR", ID)];
return state != null && (bool)state;
}
set
{
ViewState[String.Format("{0}_IR", ID)] = value;
}
}
protected override void OnLoad(EventArgs e)
{
ViewState[ID + "Text"] = Text;
base.OnLoad(e);
}
protected override void Render(HtmlTextWriter writer)
{
if (HasChildren)
{
List<Control> controls = Controls.GetControls();
List<BaseValidator> validators = Controls.GetValidators();
WriteLabelControl(writer);
WriteRequiredIndicator(writer);
WriteControlHeader(writer, validators, this.GetFirstControl());
WriteInnerControls(writer, controls);
WriteLabelEndControl(writer);
return;
}
base.Render(writer);
}
private void WriteLabelControl(HtmlTextWriter writer)
{
writer.WriteBeginTag("span");
writer.WriteAttribute("id", ClientID);
writer.WriteAttribute("class", CssClass);
foreach (string attributeKey in Attributes.Keys)
{
writer.WriteAttribute(attributeKey, Attributes[attributeKey]);
}
writer.Write(HtmlTextWriter.TagRightChar);
}
private void WriteRequiredIndicator(HtmlTextWriter writer)
{
if (IndicateRequired)
{
writer.WriteBeginTag("span");
writer.WriteAttribute("class", "requiredIndicator");
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteEndTag("span");
}
}
private void WriteControlHeader(HtmlTextWriter writer, IEnumerable<BaseValidator> validators, Control userControl)
{
writer.WriteBeginTag("label");
writer.WriteAttribute("class", "header");
if (userControl != null)
{
writer.WriteAttribute("for", userControl.ClientID);
}
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(Text);
foreach (BaseValidator validator in validators)
{
validator.CssClass = "Error";
validator.RenderControl(writer);
}
writer.WriteEndTag("label");
}
private static void WriteInnerControls(HtmlTextWriter writer, IList<Control> controls)
{
writer.WriteBeginTag("span");
writer.WriteAttribute("class", "valueContainer");
writer.Write(HtmlTextWriter.TagRightChar);
for (int i = 1; i < controls.Count; i++)
{
controls[i].RenderControl(writer);
}
writer.WriteEndTag("span");
}
private static void WriteLabelEndControl(HtmlTextWriter writer)
{
writer.WriteEndTag("span");
}
}
#region Nested type: Extensions
public static class Extensions
{
public static List<BaseValidator> GetValidators(this ControlCollection controls)
{
var validators = new List<BaseValidator>();
foreach (Control c in controls)
{
if (c is BaseValidator)
{
validators.Add(c as BaseValidator);
}
}
return validators;
}
public static List<Control> GetControls(this ControlCollection controls)
{
var listcontrols = new List<Control>();
foreach (Control c in controls)
{
if (!(c is BaseValidator))
{
listcontrols.Add(c as Control);
}
}
return listcontrols;
}
public static Control GetFirstControl(this Control container)
{
return (new InputControlFinder().FindFirstInputControl(container));
}
private class InputControlFinder
{
public Control FindFirstInputControl(Control control)
{
Control input = null;
foreach (Control child in control.Controls)
{
if (child is TextBox || child is DropDownList || child is CheckBox)
{
input = child;
}
else
{
input = FindFirstInputControl(child);
}
if (input != null)
{
return input;
}
}
return input;
}
}
}
#endregion
}

Application crashes when launching an event only in MonoTouch 4.0.1

I have an application working under MonoTouch 3.2.6;
the same application, under MonoTouch 4.0.1, crashes when launching any touch event.
Reading another question, at source, I understand that the problem lies in an object collected from the GC, but I can't see which one is. The application starts and loads dinamically the TabBar, but clicking on any TabItem crashes the app. The files main.cs and TabDelegate.cs are listed below: Main.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using IPadApp.Classes;
using AggiornamentiCL;
namespace VSViewer
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
public static UITabBar tabmain ;
public static UIViewController ctrMain;
public static Home ctrHome;
public static UIView viewMain;
public static WrapperMenu MenuManager;
public static WrapperValueStories ValueStoriesManager;
public static WrapperBibliography BibliographyManager;
public static WrapperStakeHolder StakeHolderManager;
public static Aggiornamento AggiornamentoManager;
public static string RegionId = "";
public static string RegionName= "";
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// Reperisco il RegionName dai settings
RegionName= NSUserDefaults.StandardUserDefaults.StringForKey("regione");
// Inizializzo le variabili
tabmain = tabMain;
ctrMain = ctrmain;
viewMain = viewContent;
ctrHome = new Home(String.Empty, RegionName);
// Inizializzo i manager
MenuManager= new WrapperMenu();
ValueStoriesManager= new WrapperValueStories(ref viewMain);
BibliographyManager = new WrapperBibliography();
StakeHolderManager = new WrapperStakeHolder();
AggiornamentoManager = new Aggiornamento(ctrMain);
// Imposto i delegati
tabmain.Delegate = new TabDelegate(viewMain,
ctrMain,
MenuManager,
ValueStoriesManager,
BibliographyManager,
StakeHolderManager,
AggiornamentoManager);
// Reperisco il Root Menu
MenuManager.GetRootMenu(ref tabmain);
if(string.IsNullOrEmpty(RegionName) || String.IsNullOrEmpty(Utils.GetRegionIDByName(RegionName)))
MenuManager.SoloRegioni(ref tabmain,false);
else
{
RegionId = Utils.GetRegionIDByName(RegionName);
Utils.LoadSplash(viewMain,"",RegionName);
}
// If you have defined a view, add it here:
window.AddSubview (ctrMain.View);
window.MakeKeyAndVisible ();
Thread tAggiornaDati = new Thread(new ThreadStart( Aggiornamento.AggiornaDati));
tAggiornaDati.Start();
return true;
}
}
}
TabDelegate.cs:
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using IPadApp.Classes;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
namespace VSViewer
{
public class TabDelegate : UITabBarDelegate
{
private WrapperMenu MenuManager;
private WrapperValueStories ValueStoriesManager;
private WrapperBibliography BibliographyManager;
private WrapperStakeHolder StakeHolderManager;
private Aggiornamento AggiornamentoManager;
private UIView viewMain;
//private UIViewController ctrmain;
private NodeAction previousAction ;
private int previousNode=0;
public TabDelegate (UIView pviewMain,
UIViewController pctrMain,
WrapperMenu pMenuManager,
WrapperValueStories pValueStoriesManager,
WrapperBibliography pBibliographyManager,
WrapperStakeHolder pStakeHolderManager,
Aggiornamento pAggiornamento)
{
viewMain = pviewMain;
MenuManager = pMenuManager;
ValueStoriesManager = pValueStoriesManager;
BibliographyManager= pBibliographyManager;
StakeHolderManager = pStakeHolderManager;
AggiornamentoManager = pAggiornamento;
}
private int GetSelectedTabBarIndex (UITabBar tabbar, UITabBarItem item)
{
for (int i = 0; i < tabbar.Items.Count (); i++) {
if (item == tabbar.Items[i])
return i;
}
return -1;
}
public override void ItemSelected (UITabBar tabbar, UITabBarItem item)
{
int itemSelectedIndex = GetSelectedTabBarIndex (tabbar, item);
MerqurioMenuNode currentNode = MenuManager.GetCurrentNodeByPos (itemSelectedIndex);
if (!(previousAction==currentNode.Action && previousNode == currentNode.MenuID) ||
currentNode.Action== NodeAction.OpenSubMenu)
{
// Rimuovo tutte le immagini della VS che sto abbandonando
if (previousAction== NodeAction.OpenValueStory) ValueStoriesManager.RemoveAllSlides();
// Detacho la View dell'azione precedente
foreach (UIView subView in this.viewMain.Subviews)
{
subView.RemoveFromSuperview ();
subView.Dispose();
}
// Mostro la view corretta
switch (currentNode.Action) {
case NodeAction.OpenSubMenu:
MenuManager.GetMenuByNodeId (ref tabbar, itemSelectedIndex);
// Imposto la breadcrumb
if (currentNode.ParentMenuID==0 && currentNode.Direction== NodeDirection.Forward) Breadcrumb.SetMolecola(currentNode.ViewLabel);
else if (currentNode.ParentMenuID==0 &&currentNode.Direction== NodeDirection.Backward) Breadcrumb.SetMolecola("");
Breadcrumb.UpdateBreadcrumb(currentNode.ViewLabel, AppDelegate.RegionName);
// Mostro la Splash
Utils.LoadSplash(viewMain,currentNode.ViewLabel,AppDelegate.RegionName);
break;
case NodeAction.OpenValueStory:
ValueStoriesManager.ShowValueStory (currentNode, AppDelegate.RegionId);
break;
case NodeAction.OpenBibliography:
BibliographyManager.ShowBibliography(viewMain,currentNode.FileName);
break;
case NodeAction.OpenStakeHolder:
StakeHolderManager.ShowStakeHolder(viewMain);
break;
case NodeAction.OpenRegion:
Regioni ctrRegioni = new Regioni();
this.viewMain.AddSubview(ctrRegioni.View);
break;
case NodeAction.OpenSimulator1:
Simulator_1 ctrSimulator1 = new Simulator_1();
this.viewMain.AddSubview(ctrSimulator1.View);
break;
case NodeAction.OpenSimulator2:
Simulator_2 ctrSimulator2 = new Simulator_2();
this.viewMain.AddSubview(ctrSimulator2.View);
break;
case NodeAction.OpenAggiornamento:
this.viewMain.AddSubview(AggiornamentoManager.View);
break;
default:
break;
}
}
// Aggiorno i contatori
previousAction = currentNode.Action;
previousNode = currentNode.MenuID;
}
}
}
Please help.. I can't found either the old file for MonoTouch 3.2.6...
When I look at your Main.cs file you have a pattern, except one of the things is reversed.
**tabmain = tabMain**;
ctrMain = ctrmain;
viewMain = viewContent;
I think you probably meant tabMain = tabmain;