mvvm – 在WinRT XAML UserControl中访问DataContext的位置
我有UserControlViewModel引发了一个事件:
public event EventHandler<EventArgs> StuffDone; UserControlViewModel的对象在MainPageViewModel中创建并初始化: this.userControlViewModel = new UserControlViewModel(); MainPageViewModel是MainPage的View-Model. 在MainPage.xaml中,我有以下代码将UserControlView UserControl放在MainPage中并初始化其DataContext: <views:UserControlView DataContext="{Binding userControlViewModel,Mode=OneWay}" IsHitTestVisible="False"></views:UserControlView> 到目前为止一切正常. 现在我想在UserControlView中订阅StuffDone事件.我想到的第一件事是在UserControlView的Loaded事件处理程序中执行它;但是,此时的DataContext仍然为null.扫描其余的UserControl事件完全没有任何线索. 那么,获取DataContext并订阅其事件的正确位置在哪里? 提前致谢. 解决方法
更新:WinRT for Windows 8.1支持
DataContextChanged事件.仅当您针对Windows 8的WinRT或任何不支持DataContextChanged的平台进行编码时,才使用以下内容.
似乎没有直接的方法来做到这一点,Will对他的评论建议的解决方法是最简单的方法. 以下是我的解决方案版本,对我有用: 在IDataContextChangedHandler.Generic.cs中: using Windows.UI.Xaml; namespace SomeNamespace { public interface IDataContextChangedHandler<in T> where T : FrameworkElement { void DataContextChanged(T sender,DependencyPropertyChangedEventArgs e); } } 在DataContextChangedHelper.Generic.cs中: using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace SomeNamespace { public sealed class DataContextChangedHandler<T> where T : FrameworkElement,IDataContextChangedHandler<T> { private readonly DependencyProperty internalDataContextProperty = DependencyProperty.Register( "InternalDataContext",typeof(object),typeof(T),new PropertyMetadata(null,DataContextChanged)); private static void DataContextChanged(object sender,DependencyPropertyChangedEventArgs e) { var control = sender as T; if (control == null) { return; } control.DataContextChanged(control,e); } public void Bind(T control) { control.SetBinding(this.internalDataContextProperty,new Binding()); } } } 在UserControlView.xaml.cs中: using Windows.UI.Xaml; namespace SomeNamespace { public sealed partial class UserControlView : IDataContextChangedHandler<UserControlView> { private readonly DataContextChangedHandler<UserControlView> handler = new DataContextChangedHandler<UserControlView>(); public UserControlView() { this.InitializeComponent(); this.handler.Bind(this); } public void DataContextChanged(UserControlView sender,DependencyPropertyChangedEventArgs e) { var viewModel = e.NewValue as UserControlViewModel; if (viewModel == null) { return; } viewModel.SomeEventRaised += (o,args) => VisualStateManager.GoToState(this,"TheOtherState",false); } } } 希望有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |