Showing posts with label silverlight. Show all posts
Showing posts with label silverlight. Show all posts

Saturday, January 28, 2012

A simple SilverLight object viewer

Sometimes when you're making a windows phone 7 rest client you just want to look at some of the returned data to poke see what's there. You can wire up some ui or use tracing. Maybe some breakpoints. But it's also nice to be able to drop something into the UI that you can access easily and as needed. The WinForms object browser is a handy for instance for debugging things at runtime, within the app without a debugger or a designed UI. This little widget isn't as fully functional as taht but can be helpful in a similar way. Drop it somewhere in the UI and set its DataContext property and all public readable properies will be listed with name and value. First some XAML
<UserControl x:Class="GoogleAuthDemo.ObjectBrowser"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:GoogleAuthDemo"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">
    
    <UserControl.Resources>
        <local:ObjectPropertiesConverter x:Key="ObjectPropertiesConvert"/>
        
        <DataTemplate x:Key="PropertyTemplate">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                <TextBlock Text="{Binding Key}" Margin="0,0,10,1"/>
                <TextBlock Text="{Binding Value}" TextWrapping="Wrap" TextAlignment="Right" HorizontalAlignment="Right" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
    
    <ScrollViewer>
        <ItemsControl ItemTemplate="{StaticResource PropertyTemplate}"
                      ItemsSource="{Binding Path=., Converter={StaticResource ObjectPropertiesConvert}}">                
        </ItemsControl>
    </ScrollViewer>

</UserControl>

With a smidge of C# to create a name value pair collection, given an object's properties
    public class ObjectPropertiesConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            return from p in value.GetType().GetProperties()
                   where p.CanRead
                   select new KeyValuePair<string, string>
                   (
                      p.Name,
                      p.GetValue(value, null) != null ? p.GetValue(value, null).ToString() : null
                   );                   
        }

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

Sunday, January 16, 2011

GestureBehavior and GestureTrigger

The Silverlight toolkit has a GestureService and GestureListener that allows you to pick up events from gesture input. Oddly enough it doesn't include Xaml types to easily plug those into a page and bind those events to elements and MVVM commands.

Here is an example of using a simple behavior and set of triggers that allow you to do that.

<TextBlock Text="{Binding Welcome}">
    <i:Interaction.Behaviors>
        <li:GestureBehavior/>
    </i:Interaction.Behaviors>
    <i:Interaction.Triggers>
        <li:DoubleTapTrigger>
            <cmd:EventToCommand Command="{Binding DoubleTapCommand}" PassEventArgsToCommand="True"/>
        </li:DoubleTapTrigger>
    </i:Interaction.Triggers>
</TextBlock>
The TextBlock above is bound to a ViewModel that of course has a DoupleTapCommand. In this case a RelayCommand from MVVM Light:
public MainViewModel()
{
    DoubleTapCommand = new RelayCommand<GestureEventArgs>(e =>
    {
        MessageBox.Show("double tap " + e.OriginalSource.ToString());
    });

    DragStartedCommand = new RelayCommand<DragStartedGestureEventArgs>(Drag);
    DragDeltaCommand = new RelayCommand<DragDeltaGestureEventArgs>(Drag);
    DragCompletedCommand = new RelayCommand<DragCompletedGestureEventArgs>(Drag);
}

public RelayCommand<GestureEventArgs> DoubleTapCommand
{
    get;
    private set;
}

And we can implement a quick and dirty drag and drop:
Point _start;
private void Drag(DragStartedGestureEventArgs e)
{
    UIElement ui = e.OriginalSource as UIElement;
    if (ui != null)
    {
        if (!(ui.RenderTransform is TranslateTransform))
            ui.RenderTransform = new TranslateTransform();

        TranslateTransform t = ui.RenderTransform as TranslateTransform;

        _start = new Point();
        _start.X = t.X;
        _start.Y = t.Y;

        e.Handled = true;
    }
}

private void Drag(DragDeltaGestureEventArgs e)
{
    UIElement ui = e.OriginalSource as UIElement;
    if (ui != null)
    {
        TranslateTransform t = ui.RenderTransform as TranslateTransform;

        t.X += e.HorizontalChange;
        t.Y += e.VerticalChange;
        e.Handled = true;
    }
}

private void Drag(DragCompletedGestureEventArgs e)
{
    UIElement ui = e.OriginalSource as UIElement;
    if (ui != null && _start != null)
    {
        if (MessageBox.Show("Press cancel to abort this move.", "Really?", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
        {
            TranslateTransform t = ui.RenderTransform as TranslateTransform;

            t.X = _start.X;
            t.Y = _start.Y;
            e.Handled = true;
        }
    }
}

public RelayCommand<DragStartedGestureEventArgs> DragStartedCommand
{
    get;
    private set;
}

public RelayCommand<DragDeltaGestureEventArgs> DragDeltaCommand
{
    get;
    private set;
}

public RelayCommand<DragCompletedGestureEventArgs> DragCompletedCommand
{
    get;
    private set;
}
Code and example is available here.

Sunday, December 26, 2010

Extend ViewModelLocator to be a bit more dynamic

I've been using MVVM Light in my Windows Phone development. It's lightweight, has all the base functionality I need and seems pretty solid.

One pattern that MVVM Light uses is a static ViewModelLocator class that holds all of the main/root view models in the application. You declare it as a data source in the app.xaml:
<vm:ViewModelLocator d:isdatasource="True" x:key="Locator"/>

Then in the page Xaml you can do:
DataContext="{Binding Main, Source={StaticResource Locator}}"

This is great when there is basically a 1:1 mapping between the page and the contents of each view model. What it's not so good at is dealing with the situation where you want the same page to bind to multiple view models are structurally equivalent but have different data contents.

Take for instance an RSS viewer (which coincidentally enough I'm working on at the moment). You might have a feed that represents articles form a website and another feed that is discussion posts from the same website. Each feed is further broken down into topic channels. So if we wanted to display each feed as a page, with each topic as a Pivot Item on that page we could distill the page xaml down to:
<controls:Pivot Title="{Binding Name}" 
   ItemsSource="{Binding Topics}" 
   ItemTemplate="{StaticResource RssTopicTemplate}"/>
Now if the ViewModel is statically linked to the page (as above) we need to parametrize the ViewModel as the user navigates from articles to discussions and back. It can be made to work but it violates the Single Responsibility Principle and I just don't like it.

So rather than parameterizing the ViewModel how about we parametrize the page? Let's declare the linkage between ViewModel in page on the ViewModel. We'll declare an attribute that specifies the linkage and allows a parameter to be passed the page in the form of a query string.
[Page("/RssPage.xaml?vm=ArticlesStatic")]
public class ArticlesViewModel : ViewModelBase

...

[Page("/RssPage.xaml?vm=ForumsStatic")]
public class ForumsViewModel : ViewModelBase

In this app the set of navigable items are collections of viewmodels that are displayed in ListBoxes wherein each ViewModel can be selected and navigated to:
public class ContentsViewModel : ViewModelBase
{
   public ObservableCollection<ViewModelBase> Contents 
             { get; private set; }
   public RelayCommand<object> SelectViewModel 
             { get; private set; }

   private void Select(object vm)
   {
      if (vm != null)
      {
         var page = vm.GetType().GetAttribute<PageAttribute>();
         Navigate(page.Page);
      }
   }
}
Then we need a wee bit of code in the page codebehind:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (NavigationContext.QueryString.ContainsKey("vm"))
    {
        string key = NavigationContext.QueryString["vm"];
        DataContext = ViewModelLocator.FindViewModel(key);
    }
    base.OnNavigatedTo(e);
}
where FindViewModel is a method added to the ViewModelLocator that returns the correct ViewModel using reflection:
public static object FindViewModel(string key)
{
    var prop = typeof(ViewModelLocator).GetProperty(key, 
              BindingFlags.Public | BindingFlags.Static);

    return prop.GetValue(null, null);
}

I find that moving the linkage between View and ViewModel onto the ViewModel gives us the flexibility to reuse the same UI to display the contents of multiple, structurally equivalent ViewModels, while still maintaining a loose coupling between those two layers.