MVVM-Samples icon indicating copy to clipboard operation
MVVM-Samples copied to clipboard

Different viewmodels instances of same type

Open maiorfi opened this issue 5 years ago • 2 comments

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.

maiorfi avatar Oct 17 '20 14:10 maiorfi

@Sergio0694 @jamesmcroft any tips here? Should this be something we provide an example for in the docs somewhere?

michael-hawker avatar Nov 20 '20 21:11 michael-hawker

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;
                }
            }
        }
    }

maiorfi avatar Nov 28 '20 15:11 maiorfi