将 ViewModel 传递给 UserControl

Pass ViewModel to UserControl

MySpecialView 是一个复杂的图像控件,我想从不同的角度重用它并像本例一样传递它的 ViewModel

MainWindow.xaml

<Window x:Class="YouBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:YouBug"
    mc:Ignorable="d"
    DataContext="{Binding MainViewModel}"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <local:MySpecialView ViewModel="{Binding MySpecialViewModel}"></local:MySpecialView>
</Grid>

MainViewModel

    public class MainViewModel
{
    public MySpecialViewModel MySpecialViewModel { get; set; }

    public MainViewModel()
    {
        MySpecialViewModel = new MySpecialViewModel();
        //gets not displayed!
        Task.Run(() => MySpecialViewModel.changeImage(5000, "C:\Users\user\Pictures\Capture.PNG"));
    }
}

MySpecialView.xaml

<UserControl x:Class="YouBug.MySpecialView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:YouBug"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Image Source="{Binding ImageSource}" />
</Grid>

MySpecialView.xaml.cs

    public partial class MySpecialView : UserControl
{
    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(MySpecialViewModel), typeof(MySpecialView), new FrameworkPropertyMetadata(new MySpecialViewModel(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public MySpecialViewModel ViewModel { get { return (MySpecialViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } }

    public MySpecialView()
    {
        DataContext = ViewModel;
        InitializeComponent();
    }
}

MySpecialViewModel

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

}

但是每当我从 MainViewModel 分配 MySpecialViewModels 属性时,RaisePropertyChange 事件不会强制 Image 元素或其他绑定从 MySpecialViewModel.

我在这里做错了什么?这是一种普遍的错误做法吗?

不要在视图中指定视图模型 属性,使用 DataContext。 见以下代码。

public partial class MySpecialView : UserControl
{

    public MySpecialView()
    {
        InitializeComponent();
    }
}

特殊视图模型:

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

}

在XAML特别:

    <UserControl x:Class="YouBug.MySpecialView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:YouBug"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image Source="{Binding ImageSource}" />
    </Grid>

对于主要:

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

并且在 XAML 中:

<Window x:Class="YouBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:YouBug"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <MainWindowViewModel/
</Window.DataContext>
<Grid>
    <local:MySpecialView DataContext="{Binding Path=SpecialViewModel}"></local:MySpecialView>
</Grid>

您已经习惯了“View-First-Approach”(VFA)。您的情况最好使用“ViewModel-First-Approach”(VMFA)。在 VFA 中,您从主视图放置子视图,每个子视图通过 DataContext.

链接到相应的 ViewModel

在 VMFA 中,您的 ViewModel 包含子 ViewModel 的引用。您通过 属性 绑定公开这些 ViewModel 引用,View 通过 DataTemplate.

显示它们

MainWindow.xaml

<Window x:Class="YouBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:YouBug"
    mc:Ignorable="d"
    DataContext="{Binding MainViewModel}"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <DataTemplate DataType="{x:Type vm:MySpecialViewModel}">
            <local:MySpecialViewModel />
        </DataTemplate>
    </Grid.Resources>
    <ContentControl Content={Binding MySpecialView}" />
</Grid>

MainViewModel

public class MainViewModel : ViewModelBase // Not sure why you didn't subclass ViewModelBase in your question
{
    private MySpecialViewModel _mySpecialViewModel;
    public MySpecialViewModel MySpecialViewModel
    {
        get
        {
            return _mySpecialViewModel;
        }
        set
        {
            if (value != _mySpecialViewModel)
            {
                _mySpecialViewModel = value;
                RaisePropertyChanged(); // The property changed method call
            }
        }
    }

    public MainViewModel()
    {
        MySpecialViewModel = new MySpecialViewModel();
        //gets not displayed!
        Task.Run(() => MySpecialViewModel.changeImage(5000, "C:\Users\user\Pictures\Capture.PNG"));
    }
}

MySpecialView不需要DependencyProperty,也不需要设置DataContextDataContextDataTemplate 部分自动设置。您的 MySpecialViewModel 可以保持现在的状态。

编辑

我刚刚意识到您的 MainWindow 也没有正确执行 DataContext

MainWindow.xaml.cs

public partial class MainWindow: Window
{
    public MainWindow()
    {
        InitializeComponents();
        this.DataContext = new MainViewModel();
    }
}