Answer the question
In order to leave comments, you need to log in
How to change the appearance and state of an object from a ViewModel?
Good afternoon!
I am mastering the template MVVM
and faced such a problem: there is one UserControl
that contains 2 text blocks and a switch. The switch is also UserControl
, has 2 states (on and off), looks more or less similar to the switch in Windows 10. When you click on the switch, its switching animation starts, and its current state is stored in a private variable. An event is used to change the state and appearance of the switch MouseLeftButtonDown.
Question : how can I MVVM
change the appearance and state of the switch from ViewModel
? I need to be able to change the appearance and state of the switch and clicking on it and from ViewModel.
Thank you.
update: After I formulated and asked the question, it became clear how to solve the problem. The duck method works. To change the appearance or state of an object, you can bind a method to a DependencyProperty.
Switch object model:
public class SwitchBarModel : INotifyPropertyChanged
{
private bool switchState = default(bool);
public bool SwitchState
{
get => switchState;
set
{
switchState = value;
OnPropertyChanged("SwitchState");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool State
{
get { return (bool)GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
// Using a DependencyProperty as the backing store for State. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(bool), typeof(Switch), new PropertyMetadata(<b>OnStateChanged</b>));
private static void <b>OnStateChanged</b>(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
<b> // Первой строкой обязательно приводим объект к нужному типу и вызываем нужный метод</b>
(d as Switch).ChangeState();
}
internal void ChangeState()
{
// Выполняем нужные действия по изменению внешнего вида или состояния
}
SwitchState
of the desired element. In my case, the state is changing in the collection from the ViewModel. SwitchCollection.Where(s => s.SwitchState == false)
.ToList()
.ForEach(s =>
{
s.SwitchState = true;
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question