【发布时间】:2015-09-11 21:05:56
【问题描述】:
我试图了解连接自定义控件以使用依赖属性和视图模型的最佳方式。实现依赖属性以公开可在 XAML 中用于初始化视图模型中的属性的属性。例如,在自定义控件的代码中,我可以定义以下依赖属性:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
"MyProperty", typeof(string), typeof(MyControl), new PropertyMetadata(null));
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
视图模型定义为
public class MyControlViewModel : INotifyPropertyChanged
{
public MyControlViewModel()
{
_myProperty = "Default View Model string";
}
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
自定义控件绑定到 View Model MyProperty 如下
<UserControl x:Class="MyProject.MyControlView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject">
<UserControl.DataContext>
<local:MyControlViewModel/>
</UserControl.DataContext>
<Grid>
<TextBlock Text="{Binding MyProperty}"/>
</Grid>
</UserControl>
现在,由于我已经在自定义控件的代码中定义了依赖属性 MyProperty,我希望能够使用它来初始化 ViewModel 中的 MyProperty。所以像这样的
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:MyControlView MyProperty="This was set in XAML"/>
</Grid>
</Window>
运行上述将显示在视图模型的构造函数中设置的字符串“默认视图模型字符串”。如何连接依赖属性值,以便正确初始化视图模型中的字符串?即它应该显示“这是在 XAML 中设置的”。
更新
我可以在后面的代码中设置属性更改回调,并在视图模型中设置值,即
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(string), typeof(MyControlView), new PropertyMetadata("Default", OnMyPropertyChanged));
private static void OnMyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = d as MyControlView;
if (view != null)
{
var viewModel = view.DataContext as MyControlViewModel;
if (viewModel != null)
{
viewModel.MyProperty = e.NewValue as string;
}
}
}
这是正确的,还是有味道?
【问题讨论】:
标签: wpf mvvm binding viewmodel dependency-properties