I don't understand how I can create a command to create a MVVM clickable rectangle. Here is my code:
<Rectangle x:Name="Color01" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="10,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100" MouseDown="Color_MouseDown" />
<Rectangle x:Name="Color02" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="115,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/>
<Rectangle x:Name="Color03" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="220,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/>
<Rectangle x:Name="Color04" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="325,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/>
On my first rectangle you can see I created a code behind event. First I don't know how to access my ViewModel from the code behind. Two it's not really MVVM.
public partial class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the MainWindow class.
/// </summary>
public MainWindow()
{
InitializeComponent();
Closing += (s, e) => ViewModelLocator.Cleanup();
}
private void Color_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// So what ???
}
}
I just need to be able to change a simple boolean value stored in a list stored in my viewModel when someone click on my rectangle. Why it is so complicate to do with MVVM?
Your ViewModels may not possess any references (member variables, properties, mutable/immutable fields) to any Views.
If you want to go the other way, and notify the ViewModel of user input or a similarly important event, you can use commands. Commands can be bound to properties in XAML, and are implemented by the ViewModel. They are called when the user performs a certain action, such a clicking a button.
You need to create a BindableProperty in your view's code-behind and use xaml to bind this property to the property in your view model. Then you can use the propertyChanged event of BindableProperty to apply your logic whenever the binding value changes.
In MVVM you shouldn't be accessing your view model from code behind, the view model and view are ignorant of each other a here endeth the lecture :)
Instead you can attach the EventToCommand behaviour to your control. This lets you bind an event in the control to a command in the data context. See msdn commands tutorial here.
If you are desperate to do it, you can access the controls data context property and cast it to your view model type to give access to the internals.
var vm = (ViewModelType)this.DataContext;
vm.CommandProperty.Execute(null);
Quick answer. This might help others as well
((MyViewModel)(this.DataContext)).MyProperty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With