2017-06-03 62 views
1

上午有一個場景,其中i有一個BaseImageUrl字符串
private const string BaseImageUrl = "http://eamobiledirectory.com/cooperp/Images/app_images/";綁定兩個字符串(串聯)在圖像Xamarin.Forms

對於i希望檢索到Image視圖Xaml加上串接圖像它具有精確的圖像名稱forexampleflower.jpg和反序列化JSON後得到,它是作爲一個列表的字符串值office_photo,下面是我的模型類:

public class Adverts 
    { 
      public string office_photo { get; set; } 
      public DateTime entryDate { get; set; } 
    } 

所以我想要的是如何連接BaseUrloffice_photoXAML,以便我得到圖像的完整鏈接。

下面

是我在ListView圖片:

<ListView x:Name="listViewTest" HasUnevenRows="true"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ViewCell> 
        <StackLayout Orientation="Horizontal"> 

         <Image Aspect="AspectFill" Source="{Binding office_photo}" x:Name="advertImage" 
           WidthRequest="200"/> 
        </StackLayout> 
       </ViewCell> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

回答

1

只需在視圖調制解調器中的新屬性中連接兩個字符串並綁定到該屬性。這真的很簡單,一行代碼:-)

事情是這樣的:

public string PhotoUrl { get { return BaseImageUrl + office_photo; }} 
+0

請問如何用代碼顯示 –

+0

已更新我的答案。我在手機上,所以請原諒任何錯別字... –

+0

非常感謝,它的工作哇 –

1

使用的IValueConverter

喜歡的東西

public class AddBaseUrlConverter : IValueConverter 
    { 

     #region IValueConverter implementation 

     private const string BaseImageUrl = "http://eamobiledirectory.com/cooperp/Images/app_images/"; 

     public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (value is string && ! string.IsNullOrEmpty((string)value)) { 

       return string.Format("{0}{1}", BaseImageUrl, (string)value); 
      } 
      return ""; // 
     } 

     public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 

     #endregion 
    } 

然後在你的XAML類似

<ContentPage.Resources> 
     <ResourceDictionary> 
      < AddBaseUrlConverter x:Key="cnvInvert"></AddBaseUrlConverter > 
     </ResourceDictionary> 
     </ContentPage.Resources> 

     <Image Aspect="AspectFill" Source="{Binding office_photo, Converter={StaticResource cnvInvert}}" x:Name="advertImage" WidthRequest="200"/> 

(不TES但它可以工作)

+0

將使它像這樣通過'http:// eamobiledirectory.com/cooperp /圖片/ app_images/flower.jpg' –

+0

這是個問題嗎?這應該。嘗試 –

+0

我得到'類型AddBaseUrlConverter找不到xmlns http:// xamarin.com/schemas/2014 /窗體' –