2013-04-09 54 views
2

我今天來找你一個「小」的問題。我不知道如何創建一個簡單的轉換器,因爲它第一次,我沒有找到一個簡單的例子。 我想爲gridview綁定創建一個「string to string」的轉換器。這是一個圖像源。我從一個對象的字符串(這是圖像的名字),我想補充的「完整路徑」,如:WinRT的C# - 創建轉換器字符串字符串綁定Gridview

return "ms-appdata:///local/" + value; 

其實,這是我做過什麼:

class thumbToFullPathConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     var fullPath = value; 

     return ("ms-appdata:///local/" + value); 
     Debug.WriteLine(value.ToString()); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

對不起,我認爲它是一個快速勝利,但我不知道如何做到這一點。感謝您的時間,問候。

回答

6

你想讓你的課程從IValueConverter接口繼承。

public class ThumbToFullPathConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    {   
     if (value == null)    
      return value; 

     return String.Format("ms-appdata:///local/{0}", value.ToString()); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

然後,您需要在您的XAML這個轉換器(無論是作爲一個資源本地的頁面或整個應用程序可用的應用程序資源)。導入要訪問轉換器的頁面上的命名空間。 (更改MyConverters到您的命名空間)

xmlns:local="clr-namespace:MyConverters" 

然後將它作爲一種資源

<MyPage.Resources> 
    <local:ThumbToFullPathConverter x:Key="ThumbToFullPathConverter" /> 
</MyPage.Resources> 

然後你可以使用它你喜歡的地方

<TextBlock Text="{Binding MyText, Converter={StaticResource ThumbToFullPathConverter}" /> 
2

添加一類與此代碼。這將是你的轉換器

public class ThumbToFullPathConverter : IValueConverter 
{ 
    public object Convert(object value, Type targettype, object parameter, string Path) 
    { 
     return ("ms-appdata:///local/" + value).ToString(); 
    } 
    public object ConvertBack(object value, Type targettype, object parameter, string Path) 
    { 
     throw new NotImplementedException(); 
    } 
} 

現在下面的代碼將解釋你如何可以用它來在GridView的數據綁定模板圖像。

在您的XAMl頁面添加頁面資源。

<Page.Resources> 
    <local:ThumbToFullPathConverter 
       x:Key="ThumbToFullPathConverter" /> 
</Page.Resources> 

<DataTemplate x:Key="MyTemplate"> 
    <Image 
      Source="{Binding path, Converter={StaticResource ThumbToFullPathConverter}}" 
      Stretch="None" /> 
</DataTemplate> 
+0

我不知道該感謝誰,但是謝謝這兩個作品,現在我對它的作品有個好主意! – Sw1a 2013-04-09 13:20:55