Pass ViewModel to UserControl

后端 未结 2 1486
臣服心动
臣服心动 2021-01-28 07:34

MySpecialView is a complex image control, I would like to reuse it from different views and pass its ViewModel as in this example.

MainWindow.x

2条回答
  •  孤城傲影
    2021-01-28 08:13

    Do not specify viewmodel property in you view, use DataContext. See the following code.

    public partial class MySpecialView : UserControl
    {
    
        public MySpecialView()
        {
            InitializeComponent();
        }
    }
    

    ViewModel for special:

    public class MySpecialViewModel : ViewModelBase
    {
        public BitmapSource imageSource { get; set; }
        public BitmapSource ImageSource { get { return imageSource; }
            set { if (value != imageSource)
                {
                    imageSource = value;
     RaisePropertyChanged("ImageSource");
                }
            } }
    
        public MySpecialViewModel()
        {
            //gets displayed
            ImageSource = new BitmapImage(new Uri("C:\\Users\\user\\Pictures\\test.jpg"));
    
            //gets displayed aswell
            Task.Run(() => changeImage(10000, "C:\\Users\\user\\Pictures\\clickMe.png"));
        }
    
        public async void changeImage(int sleep, string uri)
        {
            await Task.Delay(sleep);
            BitmapSource source = new BitmapImage(new Uri(uri));
            source.Freeze();
            ImageSource = source;
        }
    
    }
    

    In XAML special:

        
        
            
        
    

    For main:

    public class MainViewModel : ViewModelBase
    {
        public MySpecialViewModel SpecialViewModel
        { 
            get { return _specialViewModel; }
            set
            {
              if (value != _specialViewModel)
              {
                 _specialViewModel= value;
                 RaisePropertyChanged("SpecialViewModel");
              }
            } 
         }
    
        private MySpecialViewModel _specialViewModel;
    
            public MainViewModel()
            {
                MySpecialViewModel = new MySpecialViewModel();
                //gets not displayed!
                Task.Run(() => MySpecialViewModel.changeImage(5000, "C:\\Users\\user\\Pictures\\Capture.PNG"));
            }
        }
    

    And in XAML:

    
    
        
    
        
    
    

提交回复
热议问题