将ViewModel传递给UserControl

时间:2016-10-07 02:18:23

标签: c# wpf xaml mvvm user-controls

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

}

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

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

2 个答案:

答案 0 :(得分:3)

你已经习惯了#34; View-First-Approach&#34; (VFA)。使用&#34; ViewModel-First-Approach&#34; (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();
    }
}

答案 1 :(得分:1)

请勿在视图中指定viewmodel属性,请使用DataContext。 请参阅以下代码。

public partial class MySpecialView : UserControl
{

    public MySpecialView()
    {
        InitializeComponent();
    }
}

特殊的ViewModel:

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>