This is a mirror of official site: http://jasper-net.blogspot.com/

Binding Media Resource Streams to XAML Controls

| Sunday, March 20, 2011
I came across an interesting problem as I was working on the Windows Phone 7 client code for my next installment of the WCF Data Services blog post series on streaming. In this series, I have been using a property on my PhotoInfo entity named StreamUri to hold the URI of the image used for binding in the client UI. However, because we are dealing with a Media Link Entry (MLE), I was reminded that the correct way to get the URI of the related Media Resource (MR) on the client is by calling the GetReadStreamUri method on the DataServiceContext. This returns the value of the edit-media link for the MLE in the feed, which the service guarantees to be correct. When you rely on some property that has “Uri” in the name, your mileage may vary.

At any rate, I had thought that the obvious way to bind to the true edit-media link URI value was to extend my entity definition (since it’s a partial class) to add a StreamUri property that calls the GetReadStreamUri method in the getter. This works great for read-only binding. However, there is a flaw to doing it this way. Can you guess it? When you create a new MLE with a binary MR stream, the client first sends a POST to create the MR followed by the MLE, with default values. The client sends second a MERGE request to update the new MLE with client values. The problem is that the client doesn’t know that the StreamUri extension property isn’t part of the entity defined in the data service. Hence, poof! An error in the data service during the MERGE operation “I don’t know what to do with this StreamUri property.”

Since my client application (in this case WP7) is XAML-based, value converters to the rescue! Instead, I defined a converter that takes my entity object binding and returns the URI to which to bind, as follows:

public class StreamUriConverter : IValueConverter 
    public object Convert(object value, Type targetType, 
        object parameter, System.Globalization.CultureInfo culture) 
    { 
        // Return the URI of the media resource stream for binding. 
        return App.ViewModel.Context.GetReadStreamUri(value); 
    }

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

And here’s what the XAML looks like (I should mention that because the root DataContext of the page is set to my DataServiceCollection<PhotoInfo> binding collection and the Image is in a ListBox control, the default binding is to a PhotoInfo object):

… 
<StackPanel.Resources> 
    <converter:StreamUriConverter x:Key="getStreamUri" /> 
</StackPanel.Resources> 
<Image Source="{Binding Converter={StaticResource getStreamUri}}" 
        Height="75" Width="50" />  
… 

Posted via email from Jasper-net

0 comments: