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"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">
        <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" />
        <ItemsControl ItemTemplate="{StaticResource PropertyTemplate}"
                      ItemsSource="{Binding Path=., Converter={StaticResource ObjectPropertiesConvert}}">                


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.GetValue(value, null) != null ? p.GetValue(value, null).ToString() : null

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

No comments:

Post a Comment