views:

282

answers:

1

Is it possible to bind a rows in a Silverlight DataGrid to some sort of style property in a ViewModel so that styles can be applied programatically / dynamically?

I've been using the Mvvm-Light toolkit quite successfully to create an mvvm silverlight app, this is the first major stumbling block I have hit.

Thanks in advance for any help.

A: 

There is no data template selector or type specific data templates in Silverlight. One way to work around this is to have a property in your ViewModel that triggers the visibility of something in the XAML. For instance, have an element in your your DataGrid's item template where the Visibility is bound to a property like IsSelected in your ViewModel, and use a BooleanToVisibility value converter.

<DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="130" />
            <ColumnDefinition Width="70" />
            <ColumnDefinition Width="70" />
            <ColumnDefinition Width="50" />
        </Grid.ColumnDefinitions>

        <Grid Grid.ColumnSpan="4"
              Visibility="{Binding Path=IsSelected, Converter={StaticResource BoolToVisibilityConverter}}">
            <Border Style="{StaticResource SelectedDataGridRowStyle}" />
        </Grid>
        <!-- other stuff here -->
    </Grid>
</DataTemplate>

In case you haven't defined your own Boolean to Visbility value converter yet ...

public class BoolToVisibilityConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var visible = true;
        if (value != null && value is bool)
            visible = (bool)value;

        var reverse = false;
        if (parameter != null)
            reverse = System.Boolean.Parse((string)parameter);

        visible = reverse ? !visible : visible;

        return visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var visibility = System.Windows.Visibility.Visible;
        if (value != null && value is System.Windows.Visibility)
            visibility = (System.Windows.Visibility)value;

        var reverse = false;
        if (parameter != null && parameter is bool)
            reverse = (bool)parameter;

        var visible = visibility == System.Windows.Visibility.Visible;

        visible = reverse ? !visible : visible;

        return visible;
    }
}
Matt Casto
Thats great! thanks for taking the time to write that.
bplus