Binding a HTML control into a stacklayout using xamarin forms - c#

Being a newbie to Xamrin I am struggling to adding some HTML to a StackLayout via Xamarin Forms. I have tried quite a few things and had a Google around.
Firstly I can't work out which bindable object I am supposed to be using. As I cannot find a straight answer on Google/Xamarin I am going to assume this is not as easy I was hoping.
var nameEntry = new Label ();
nameEntry.SetBinding (Label.TextProperty, "Club.ClubName");
var webView = new WebView ();
webView.SetBinding ( ??? , "Club.Description");
var content = new StackLayout {
Children = {
nameEntry,
???
}
};
I am not sure if this is possible within Xamarin forms itself. Can anyone help?
I should point out my data for the form is being retrieved asynchronously on a remote json endpoint
protected override void OnAppearing ()
{
base.OnAppearing ();
if (ViewModel == null || ViewModel.IsLoading)
return;
ViewModel.LoadItemsCommand.Execute (Club.ClubId);
}
My remote json api contains, Description contatins a HTML snippet which I would like to use.
{
ClubName: "Stourbridge",
Description: "<p>This club meets every TWO weeks on a <b>Friday</b>.</p>"
...
}

Try the following example that will show how to do the bindings.
Note that you have to use a HtmlWebViewSource to achieve this, and bind the WebView.Source to this.
Clicking the button will change the view model and update the WebView appropriately to the newly changed text.
StackLayout objStackLayout = new StackLayout();
MyView objMyView = new MyView();
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text</p></body></html>";
HtmlWebViewSource objHtmlWebViewSource = new HtmlWebViewSource();
objHtmlWebViewSource.SetBinding(HtmlWebViewSource.HtmlProperty, "MyHtml");
objHtmlWebViewSource.BindingContext = objMyView;
WebView objWebview = new WebView();
objWebview.HorizontalOptions = LayoutOptions.FillAndExpand;
objWebview.VerticalOptions = LayoutOptions.FillAndExpand;
objWebview.Source = objHtmlWebViewSource;
Button objMyButton2 = new Button();
objMyButton2.Text="Change Html";
objMyButton2.Clicked+=((o2,e2)=>
{
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text that has changed.</p></body></html>";
});
objStackLayout.Children.Add(objMyButton2);
objStackLayout.Children.Add(objWebview);
The view model is just a simple one with a bindable property as below:-
public class MyView
: Xamarin.Forms.View
{
public static readonly BindableProperty MyHtmlProperty = BindableProperty.Create<MyView, string>(p => p.MyHtml, default(string));
public string MyHtml
{
get { return (string)GetValue(MyHtmlProperty); }
set { SetValue(MyHtmlProperty, value); }
}
}
Before clicking the button gives:-
After clicking the button, adjusts the view model, and automatically updates the control via the binding giving:-

Related

Creating view with json (Xamarin.Forms)

I'm facing several issues.
I want to deserialize my json to create Views.
I want to create view, so I created a json model who describe my page with several views in it. I have created classes who's going to create my views. Before the json I was doing this in static:
ElementModel element = new ElementModel();
element.Width = 100;
element.Height = 40;
element.Top = 0;
element.Left = 0;
element.Label = "Element num 1";
element.IsEnabled = true;
element.IsMandatory = false;
ElementView ev1 = new TextBoxView(element);
al.Children.Add(ev3.getView());
this.Content = new ScrollView { Content = al };
And it worked fine, this code above was creating an Entry view placed with top, left informations and the width, height dimensions in the json.
I wanted something more dynamic so I created a json, I deserialize it and after that I create my views.
ScrollView sv;
RelativeLayout rl;
AbsoluteLayout al;
public MainPage()
{
InitializeComponent();
al = new AbsoluteLayout();
testDeserialize();
//I was creating view with this function before
//testView();
}
public void testDeserialize()
{
string json = #"myjson in the link";
string newjson = json.Replace("'", "\'");
TourApplication ta = JsonConvert.DeserializeObject<TourApplication>(newjson);
models.Page p = ta.Pages.ElementAt(0);
ElementView ev=null;
foreach (ElementModel em in p.Elments)
{
//ev = new TextBoxView(em);
//al.Children.Add(ev.getView()); doesn't work
Console.WriteLine("-----------------------"+em.Label);
}
this.Content = new ScrollView { Content = al };
}
The creation doesn't work but I'm doing the same operation when it was working.
I have no idea what I can do to fix this.
You can find in this link the json with the generated class structure.
Thx for your help.
EDIT : The problem was due to my json, now I can have my Views. But only one of my View is editable. I mean for the others the keyboard doesn't show.

Update WPF with externalevent and MVVM schema

I'm currently developping a new soft which analyze a lot of data on Revit.
I have my WPF View, my ViewModel and a long methode.
init.cs:
IExternalEventHandler handlerEvent = new FamilyAnalysis();
var familyAnalysisEvent = ExternalEvent.Create(handlerEvent);
Gui = new AnalysisView(familyAnalysisEvent);
Gui.Show();
AnalysisView.xaml.cs:
public AnalysisView(ExternalEvent externalEvent)
{
InitializeComponent();
Windows.SetLocation(this);
Language = System.Windows.Markup.XmlLanguage.GetLanguage(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
DataContext = new AnalysisViewModel(externalEvent, this);
}
AnalysisViewModel.cs:
public ICommand StartAnalysisCommand
{
get
{
return _startAnalysisCommand ?? (_startAnalysisCommand = new RelayCommand(() =>
{
//Some check before then..
_externalEvent.Raise();
}));
}
}
during the _externalEvent.Raise() I would like to have a loading form updating the state of the methode.
I tried to search about dispatcher but I'm not sure how to do that and all my try didn't worked. The loading screen pop but the value are not getting updated.
Any advice ?

How to change the title of Timepicker and localization in custom renderer

I have Xamarin forms time picker following custom renderer for IOS
[assembly: ExportRenderer(typeof(TimePicker), typeof(Time24PickerRenderer))]
namespace LabOraTimeStamp.iOS.Renderers
{
public class Time24PickerRenderer:TimePickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
{
base.OnElementChanged(e);
var timePicker = (UIDatePicker)Control.InputView;
timePicker.Locale = new NSLocale("no_nb");
//Get the Done button
var toolbar = (UIToolbar)Control.InputAccessoryView;
var doneBtn = toolbar.Items[1];
//Set the Done to OK
doneBtn.Title = "OK";
}
}
}
I wanted to change the default "done" to "Ok".
1) How can I do that? the line mentioned above for setting the title does not affect anything.
2) I already implemented localization for xamarin forms.I just wanted to use existing Resx values from custom renderer to show the string for appropriate culture.How can I achieve that?
So the reason why your code isn't working is because the done button is created with the UIBarButtonSystemItem.Done style. It doesn't care about the Title property. Renderer code here.
To work around that issue you could try replacing the Xamarin created done button with your own custom Ok button.
//Get the Done button
var toolbar = (UIToolbar)Control.InputAccessoryView;
// Replace Xamarin's buttons with custom ones.
var spacer = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
var doneButton = new UIBarButtonItem();
doneButton.Title = "OK";
doneButton.Clicked += (o, a) => Control.ResignFirstResponder();
toolbar.SetItems(new [] { spacer, doneButton}, false);

visual studio xamarin forms mvvm

I'm starting a new project, and id like to use MVVM - I really like this pattern, and I have been using it in all my windows phone 8.1 apps. But moving to xamarin is a jungle! I usually use mvvm light, and I have a nice basic implementation I use every time a create a new project - but I can't find a really good sample that shows exactly what I need.
What I want to do is make a xamarin shared (or portable) project, that shares the views across all platforms. I want to write create the view using code-behind - so no xaml.
Does anyone have experience with this and can point me to a good sample?
I'm also wondering if I need to use a thirtyparty framework afterall, since navigating seems pretty easy.
There are many samples on to be found. My favorite site for Xamarin.Forms samples is Xamarin Forms in Anger.
Let's take a look at the Jobbberr sample:
using System;
using Xamarin.Forms;
namespace InAnger.Jobbberr
{
public class SettingsPage : ContentPage
{
public SettingsPage ()
{
Style = AppStyle.SettingsPageStyle;
var pageTitle = new Frame () {
Style = AppStyle.PageTitleLabelFrameStyle,
Padding = new Thickness(0,Device.OnPlatform(15,0,0),0,10),
Content = new Label {
Style = AppStyle.PageTitleLabelStyle,
Text = "Settings",
}
};
var signoutButton = new Button () {
VerticalOptions = LayoutOptions.EndAndExpand,
HorizontalOptions = LayoutOptions.Center,
Text = "Sign Out",
TextColor = AppStyle.DarkLabelColor,
};
Content = new StackLayout {
VerticalOptions = LayoutOptions.FillAndExpand,
Padding = new Thickness (20),
Children = {
pageTitle,
new BoxView() {
HeightRequest = 1,
BackgroundColor = AppStyle.DarkLabelColor,
},
new SettingsUserView(),
new SyncView (),
new SettingsSwitchView ("GPS"),
new SettingsSwitchView ("Jobs Alert"),
signoutButton,
new StatusBarView()
}
};
}
}
}
What do you see here?
The new class SettingsPage derives from ContentPage. The controls pageTitle and signoutButton are created in its constructor. In the end you see how a StackLayout is being created, filled with the controls and set as content of the page. That's how to create a Page in code.
How to apply MVVM?
Set BindingContext = ViewModel in the first row of the constructor (create a new view model or locate it by via a ViewModelLocator or anything).
Let's say for example you want to bind the Text and Command property of signoutButton to the view model's properties SignOutButtonText and SignoutCommand. You would change the creation of the button to this:
var signoutButton = new Button () {
VerticalOptions = LayoutOptions.EndAndExpand,
HorizontalOptions = LayoutOptions.Center,
TextColor = AppStyle.DarkLabelColor,
};
signoutButton.SetBinding(Button.TextProperty, "SignOutButtonText");
signoutButton.SetBinding(Button.CommandProperty, "SignoutCommand");

Tab bar Event on selected next tab

How to get Event on selected next Tab
Want to load next tab view controller after event trigger.
It create two tab bar for IOS mobile application.
public class TabBarController : UITabBarController {
UIViewController infoController, relatedController,
public TabBarController ()
{
infoController = new UIViewController();
infoController.Title = "Info";
infoController.TabBarItem = new UITabBarItem ("Info", UIImage.FromFile("/Images/first.png"), 0);
infoControllerView.BackgroundColor = UIColor.Orange;
relatedController = new UIViewController();
relatedController.Title = "Related";
relatedController.TabBarItem = new UITabBarItem ("Related", UIImage.FromFile("/Images/second.png"), 1);
relatedController.View.BackgroundColor = UIColor.Orange;
var tabs = new UIViewController[] {
infoController, relatedController
};
ViewControllers = tabs;}}
Second tab will load after a service call result.
based on response data will show result.
Want to know and Event for tab-bar selected tab.
#All
Thanks you in advance.

Categories

Resources