MVVM updating of view element
-
20-12-2019 - |
Question
I have an app following the MVVM scheme. Where I have multiple View and viewmodels. On my mainPage I have a textblock that I would like to update with information from chosen elements.
Upon starting the app I insert a value from the mainviewmodel to test the binding so everything works here. Where the code is as follows:
<TextBlock Text="{Binding colorOfElement}" Grid.Row="1"/>
Code in mainviewmodel
private string _colorOfElement;
public string colorOfElement
{
get
{
return _colorOfElement;
}
set
{
_colorOfElement = value;
NotifyPropertyChanged("colorOfElement");
}
}
......
colorOfElement = "Test";
This is displayed correctly. When a user then interacts with an element an event is fired inside the new viewmodel, in here I have a reference to the mainviewmodel so I can easily update the string colorOfElement.
private MainViewModel mv;
......
public void MouseDown(ManipulationStartedEventArgs obj)
{
FrameworkElement MovingElement = (FrameworkElement)obj.OriginalSource;
Canvas canvas = FindParentOfType<Canvas>(MovingGear);
obj.ManipulationContainer = canvas;
obj.Handled = true;
testViewModel viewModel = (testViewModel)MovingElement.DataContext;
mv.colorOfElement = viewModel.model.Color;
}
when this function executes I am send into the mainviewmodel and NotifyPropertyChanged is fired. But on the Application.Page that shows the view I cannot see any update of the variable but in the code the variable changes. Any idea for this binding problem?
Answer As I had tested the datacontext and everything was working the problem was in my public class.
public class MainViewModel : ViewModelBase
Here It should include the INotifyPropertyChanged interface to enable the feature. So the simple solution is to add this and get:
public class MainViewModel : ViewModelBase, INotifyPropertyChanged
Then you are good to go :)
Solution
Ensure that:
- DataContext is set to the right instance of the MainViewModel
- the MainViewModel implements the INotifyPropertyChanged Interface