2016-02-06 35 views
0

作爲Xamrin的新手,我正努力通過Xamarin Forms向StackLayout添加一些HTML。我嘗試了很多東西,並且附近有Google。使用xamarin形式將HTML控件綁定到堆棧佈局

首先,我不能確定我應該使用哪個可綁定對象。由於我無法在Google/Xamarin上找到直接的答案,我會認爲這並不像我期望的那麼容易。

var nameEntry = new Label(); 
nameEntry.SetBinding (Label.TextProperty, "Club.ClubName"); 

var webView = new WebView(); 
webView.SetBinding (??? , "Club.Description"); 

var content = new StackLayout { 

Children = { 
    nameEntry, 
    ??? 
    } 
}; 

我不確定這是否可能在Xamarin形式本身。誰能幫忙?

我要指出我的數據的形式被異步檢索上的遠程JSON端點

protected override void OnAppearing() 
    { 
     base.OnAppearing(); 

     if (ViewModel == null || ViewModel.IsLoading) 
      return; 

     ViewModel.LoadItemsCommand.Execute (Club.ClubId); 
    } 

我的遙控JSON API包含,說明contatins一個HTML片段,我想用。

{ 
    ClubName: "Stourbridge", 
    Description: "<p>This club meets every TWO weeks on a <b>Friday</b>.</p>" 
    ... 
} 

回答

1

請嘗試以下示例,以顯示如何執行綁定。

請注意,您必須使用HtmlWebViewSource來實現此目的,並綁定WebViewSource這個。

單擊該按鈕將更改視圖模型並將WebView更新爲適合新更改的文本。

 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); 

視圖模型只是一個簡單的用綁定屬性如下: -

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); } 
    } 

} 

之前單擊按鈕給出: -

enter image description here

點擊按鈕後,調整視圖模型,並通過綁定自動更新控件: -

enter image description here

+0

謝謝很好解釋,現在看... – Rippo