Reputation: 747
Assume I have the view with DataGrid. Also I have the view-model with the collection of some objects. DataGrid binds to the collection. The target is setting the color of row depends on value of object's property. Regarding on MVVM is it right way to do it in code-behind like code below ?
private void ScheduleGrid_OnLoadingRow(object sender, DataGridRowEventArgs e)
{
var schedule = e.Row.DataContext as OrderScheduleModel;
if(schedule==null)
return;
if (schedule.Date.DayOfWeek == DayOfWeek.Saturday || schedule.Date.DayOfWeek == DayOfWeek.Sunday)
{
e.Row.Background = new SolidColorBrush(Color.FromArgb(0xff, 0x90, 0xee, 0x90));
}
}
I know I could create behavior, attached property, style, etc. But basically, does MVVM allow to do manipulations with view _based_on_view-model_ in code-behind ?
Upvotes: 2
Views: 380
Reputation: 5117
Assume:
Converter:
public class DobToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is DateTime)
{
var brush = new SolidColorBrush(Colors.Transparent);
var dob = (DateTime)value;
if (dob.Year <= 2000)
{
brush.Color = Colors.LightGray;
}
return brush;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<Grid>
<Grid.Resources>
<local:DobToColorConverter x:Key="DobToColor" />
</Grid.Resources>
<DataGrid ItemsSource="{Binding People}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding Dob, Converter={StaticResource DobToColor}}" />
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
Output:
Upvotes: 1
Reputation: 37760
The goal of MVVM, as a pattern, is to separate view from view model and model.
The bunch of MVVM and XAML assumes, that view and view model use data binding to communicate each other. Data binding is, probably, the best way, but not the only way. Until your code doesn't bring UI logic into VM and vice versa, this is still MVVM.
From this point, code sample from the question is OK.
Upvotes: 1