非常感谢你的帮助。
我试图通过一个小例子来理解 ViewToViewModel 属性。我有几个问题。我的代码如下。
[ViewToViewModel] 属性是否应该放置在 View、ViewModel 或两者中?
如果我尝试使用属性 MappingType,例如:[ViewToViewModel, MappingType = ...] MappingType 会给我一个错误。我是否缺少“使用”语句/程序集参考?有语法的例子吗?
我能够让事情按照我需要的方式工作,但我认为我没有让“ViewToViewModel”部分正常工作。在用户控件的代码隐藏中,属性更改在 HandleMyName(object e) 中处理。ViewToViewModel 应该这样做吗?
意见:
- 主窗口
- 用户控制视图
视图模型:
- 主窗口视图模型
- 用户控制视图视图模型
主窗口
<catel:DataWindow x:Class="ViewToViewModelStudy.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://catel.codeplex.com"
xmlns:uc="clr-namespace:ViewToViewModelStudy.Views" >
<StackPanel x:Name="LayoutRoot">
<Label Content="{Binding Title}" />
<uc:UserControlView MyName="{Binding Title}" />
</StackPanel>
</catel:DataWindow>
.
用户控件视图.xaml
<catel:UserControl x:Class="ViewToViewModelStudy.Views.UserControlView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://catel.codeplex.com">
<StackPanel>
<TextBlock>Innerview Model</TextBlock>
<TextBlock Text="{Binding MyName}"></TextBlock>
<TextBlock>Innerview Model</TextBlock>
</StackPanel>
</catel:UserControl>
UserControlView.xaml.cs
namespace ViewToViewModelStudy.Views
{
using Catel.Windows.Controls;
using Catel.MVVM.Views;
using System.Windows;
using System.Data;
public partial class UserControlView : UserControl
{
[ViewToViewModel]
public string MyName
{
get { return (string)GetValue(MyNameProperty); }
set { SetValue(MyNameProperty, value); }
}
public static readonly DependencyProperty MyNameProperty =
DependencyProperty.Register(
"MyName",
typeof(string),
typeof(UserControlView),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnMyName)));
static void OnMyName(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
UserControlView ic = (UserControlView)obj;
ic.HandleMyName(e.NewValue);
}
private void HandleMyName(object e)
{
ViewModels.UserControlViewModel vm = (ViewModels.UserControlViewModel)this.ViewModel;
if (vm != null)
{
vm.MyName = e.ToString(); // << Shouldn't this happen automagically?
}
}
public UserControlView()
{
InitializeComponent();
}
}
}
用户控制视图模型.cs
namespace ViewToViewModelStudy.ViewModels
{
using Catel.MVVM;
using Catel.Data;
using Catel.MVVM.Views;
using Catel.Windows.Controls;
public class UserControlViewModel : ViewModelBase
{
public UserControlViewModel()
{ }
public string MyName
{
get { return GetValue<string>(MyNameProperty); }
set { SetValue(MyNameProperty, value); }
}
public static readonly PropertyData MyNameProperty = RegisterProperty("MyName", typeof(string), null, (sender, e) => ((UserControlViewModel)sender).OnMyPropertyChanged());
private void OnMyPropertyChanged()
{
}
}
}