Dependency Property vs InotifyPropertyChanged in ViewModel f

本文关键字:ViewModel in InotifyPropertyChanged Property vs Dependency | 更新日期: 2023-09-27 18:37:01

我创建了空白的C#/XAML Windows 8应用程序。添加简单的 XAML 代码:

<Page
    x:Class="Blank.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel
            Margin="0,150"
            HorizontalAlignment="Center">
            <TextBlock
                x:Name="xTitle"
                Text="{Binding Title, Mode=TwoWay}"/>
            <Button Content="Click me!" Click="OnClick" />
        </StackPanel>
    </Grid>
</Page>

以及 C# 部分中的简单代码:

public sealed partial class MainPage
    {
        private readonly ViewModel m_viewModel;
        public MainPage()
        {
            InitializeComponent();
            m_viewModel = new ViewModel
            {
                Title = "Test1"
            };
            DataContext = m_viewModel;
        }
        private void OnClick(object sender, RoutedEventArgs e)
        {
            m_viewModel.Title = "Test2";
        }
    }

现在我想实现ViewModel.我有两种方法:

  1. 使用依赖项属性
  2. 实现 INotifyPropertyChanged

对于第一种方法,它是:

public class ViewModel : DependencyObject
    {
        public string Title
        {
            get
            {
                return (string)GetValue(TitleProperty);
            }
            set
            {
                SetValue(TitleProperty, value);
            }
        }
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string)
            , typeof(ViewModel)
            , new PropertyMetadata(string.Empty));
    }

第二是:

public class ViewModel : INotifyPropertyChanged
    {
        private string m_title;
        public string Title
        {
            get
            {
                return m_title;
            }
            set
            {
                m_title = value;
                OnPropertyChanged("Title");
            }
        }
        protected void OnPropertyChanged(string name)
        {
            if (null != PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }

我更喜欢第一种方式,因为它允许使用强制(Silverlight for web和WP7没有强制功能)。WinRT也是..但我仍然在寻找和希望),对我来说看起来更自然。但不幸的是,它作为第一种方法的一次性工作。

谁能向我解释为什么MS放弃使用依赖属性来实现视图模型?

Dependency Property vs InotifyPropertyChanged in ViewModel f

不应在 ViewModel 中使用 DependencyProperty,而应仅在控件中使用它们。 您永远不希望将一个 ViewModel 绑定到另一个视图模型,而且 ViewModels 不需要保留其值,也不需要提供默认值,也不需要提供属性元数据。

您应该只在视图模型中使用 INotifyPropertyChanged。