Creating a Converter to take an ID and create an I

2020-05-06 09:20发布

问题:

I am using a WCF weather service and receiving weather information like ID, Description, and Images. It returns like this:

<WeatherDescription>
    <WeatherID>1</WeatherID>
    <Description>Thunder Storms</Description>
    <PictureURL>
     http://ws.cdyne.com/WeatherWS/Images/thunderstorms.gif
    </PictureURL>
</WeatherDescription>

Now in the XAML I am showing my data in a dataGrid as so:

<sdk:DataGridTextColumn Header="ID" Binding="{Binding WeatherID}" />

The above binding is to another function of the service that returns a 7 day forecast but returns the same weather ID that works with the weather description. I created an array of all the Weather Descriptions on the code side like so:

public partial class MainPage : UserControl
{
    //array of weather descriptions
    private WeatherDescription[] weatherInformation;

    WeatherSoapClient weatherClient = new WeatherSoapClient();

    public MainPage()
    {
        InitializeComponent();
        weatherClient.GetWeatherInformationCompleted += new EventHandler<GetWeatherInformationCompletedEventArgs>(weatherClient_GetWeatherInformationCompleted);
        weatherClient.GetWeatherInformationAsync();
    }

    void weatherClient_GetWeatherInformationCompleted(object sender, GetWeatherInformationCompletedEventArgs e)
    {
        weatherInformation = e.Result;
    }
}
  1. What I want to do is create a converter that takes the ID from that Column and converts it to an image using the URL supplied in the weather descriptions.

  2. I know Silverlight does not support GIF's so I would like to send that image to a handler that would convert it to a JPG.

Being brand new to both Silverlight and C# these are two things that I am really having trouble with. Thank you for the help in advance! And code snippets are the best help for me since I do not understand a lot of C# yet.

回答1:

  1. For the converter, you can do something like this:

    <sdk:DataGrid>

    <sdk:DataGrid.Resources>
        <local:WeatherIdToImageConverter key="IdToImageConverter" />
    </sdk:DataGrid.Resources>
    ...
        <sdk:DataGridTemplateColumn>
           <sdk:CellTemplate>
               <DataTemplate>
                   <Image Source="{Binding WeatherID, Converter={StaticResource IdToImageConverter}}" />
                   ...
    
  2. In your implementation of the converter, I would use the ImageTools library (http://imagetools.codeplex.com/) to convert between GIF and PNG (PNG will be better quality than JPEG).