Different viewmodels instances of same type
Hi.
Should I use, say, 2 instances of same viewmodel in 2 different views (e.g. side-by-side panels), how could I initialize such viewmodels properly (e.g. passing "left" and "right" context/initialization argument to each viewmodel)?
Thanks.
@Sergio0694 @jamesmcroft any tips here? Should this be something we provide an example for in the docs somewhere?
As a reference (but I'm not sure this can be considered the "right" pattern), I did it this way:
(say SampleHeartbeatDetector is a view/UserControl I need to create two times, through dependency injection as transient services, with different initialization parameter "HeartBeatIdentifier")
Containing View:
<StackPanel>
<views:SampleHeartbeatDetector HeartBeatIdentifier="HEARTBEAT_TOPIC_1"></views:SampleHeartbeatDetector>
<views:SampleHeartbeatDetector HeartBeatIdentifier="HEARTBEAT_TOPIC_2"></views:SampleHeartbeatDetector>
</StackPanel>
ViewModel:
public class SampleHeartbeatDetectorViewModel : ObservableRecipient
{
public string HeartbeatTopicToBeDetected { get; set; }
}
View/UserControl CodeBehind:
public partial class SampleHeartbeatDetector : UserControl
{
private string _heartBeatIdentifier;
public SampleHeartbeatDetector()
{
DataContext = App.Current.Services.GetService<SampleHeartbeatDetectorViewModel>();
InitializeComponent();
}
public string HeartBeatIdentifier
{
get => _heartBeatIdentifier;
set
{
_heartBeatIdentifier = value;
if (!string.IsNullOrEmpty(_heartBeatIdentifier))
{
(DataContext as SampleHeartbeatDetectorViewModel).HeartbeatTopicToBeDetected = _heartBeatIdentifier;
}
}
}
}