Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF non-static commands implementation possible?

Tags:

c#

wpf

Is there a way to create "Instance only" ICommand implementation for Custom Control, WITHOUT static classes "behind"?

I am trying to update previously created custom control.

One of the goals is to ensure multiinstance capability.

If two or more instances of the same custom control was used in the same application, there is (as expected) interferences from any static clases that are used behind.

I figured out how to get rid of the most, but having troubles with ICommand.

Given GUI items on the Custom Control have Command that must be only valid within the User Control instance - instead of this now the Command is interfering with all instances (as example CanExecute makes GUI items active on UserControl Instances where the "local" conditions are not met).

like image 524
user1608721 Avatar asked Feb 06 '26 05:02

user1608721


2 Answers

You can create your command and expose it as a property of your ViewModel, then bind to it in your control:

In your ViewModel:

public ICommand MyCommand {get;set;} // construct your command and set it here

in your control:

<Button Command="{Binding MyCommand}"/>

if you are not using MVVM pattern, then you should create the same field in your DataContext (probably in your controls code behind)

you can also use Dependency properties in order to define your command, if you change your command after your user control is created, you should use it.

In general:

In order to know your options when writing in WPF / C# I recommend reading about MVVM pattern, dependency properties, DataContext and Binding - you may know some of this already.

like image 126
Ron.B.I Avatar answered Feb 08 '26 20:02

Ron.B.I


I think you might be confused by the fact that the CanExecute and Execute methods do not have a parameter linking them to the object upon which they are supposed to act.

But remember that the ICommand interface must be implemented by a class, and objects of that class can and should have fields, typically initialized in the constructor.

For example, if you follow the MVVM pattern (as already mentioned by Ron.B.I.), the command typically has a reference to the viewmodel. Or you can use something like a RelayCommand, and capture the viewmodel in a delegate or lambda closure object.

like image 45
Kris Vandermotten Avatar answered Feb 08 '26 19:02

Kris Vandermotten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!