The logic behind changing the style of a button, text, and a whole heap is in View.cs in separate methods.

But these methods need to be called from the ViewModel.

How to organize, that from ViewModel it was possible to call a method on state change View?

  • Do you have exactly mvvm? Strangely simple - Sergey
  • View.cs is code behind that? - Sergey

1 answer 1

See it.

If you need to change the data, you simply change it in the VM, and that's it, View picks it up through a binding.

If you need to change the visual state, then you do it not in the VM, but in the View.

If you need to change the visual state in response to the changed data , it is usually done this way: the visual state is calculated through a converter, and it is applied.

Example: let you need to change the background color depending on the value. For values ​​from 1 to 3 red, from 4 to 10 yellow, more green. We do this:

Converter:

 class ButtonColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var note = (int)value; var color = note <= 3 ? Colors.Red : note <= 10 ? Colors.Yellow : Colors.Green; return new SolidColorBrush(color); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

XAML:

 <Window x:Class="Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Test" Height="150" Width="150"> <Window.Resources> <local:ButtonColorConverter x:Key="ButtonColorConverter"/> </Window.Resources> <Grid> <Button Content="{Binding}" Background="{Binding Converter={StaticResource ButtonColorConverter}}"/> </Grid> </Window> 

Result:

animated cartoon