【发布时间】:2012-06-15 19:47:38
【问题描述】:
我创建了空白 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。我有两种方法:
第一种方法是:
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;
}
我更喜欢第一种方式,因为它允许使用coerce(Silverlight 用于 web 和 WP7 没有coerce 功能.. WinRT 也是.. 但我仍在寻找和希望)并且看起来更自然为了我。但不幸的是,对于第一种方法,它的作用是OneTime。
谁能向我解释为什么 MS 放弃使用 Dependency Property 来实现视图模型?
【问题讨论】:
-
@lukas 我知道利弊。但是依赖属性的方式不能正常工作(仅作为
OneTime)
标签: c# windows-8 microsoft-metro inotifypropertychanged dependencyobject