[英]How to create datacontextchanged event in windows phone 8 silverlight
I want to extent my UserControl class so that it could have datacontextchanged event in it, as it is in a Windows phone xaml
application. 我想扩展我的UserControl类,以便它可以在其中具有datacontextchanged事件,就像在Windows Phone
xaml
应用程序中一样。
But I am unable to find that event. 但是我找不到那个事件。
This DataContextChangedEventArgs is in xaml based application in windows phone but when project is created in silverlight not able to find that event 此DataContextChangedEventArgs在Windows Phone的基于xaml的应用程序中,但是在Silverlight中创建项目时找不到该事件
[Disclaimer: I'm not a WindowsPhone developer, so everything I say about mobile Silverlight is based on the stuff I read on msdn (but never tried out myself) and the stuff I know from working with the ordinary fullfledged-browser Silverlight] [免责声明:我不是Windows Phone开发人员,所以我所说的有关移动Silverlight的内容都是基于我在msdn上阅读的内容(但从未尝试过),以及与普通的功能齐全的浏览器Silverlight一起工作所了解的内容。
The DataContextChanged event is only supported in Silverlight 5. The mobile version of Silverlight (as far as I know) is based on Silverlight 4. That means you have to implement the event yourself. 仅在Silverlight 5中支持DataContextChanged事件。据我所知,Silverlight的移动版本基于Silverlight4。这意味着您必须自己实现该事件。 Just define a dependency property of type object in your UserControl and directly bind against the DataContext.
只需在UserControl中定义类型为object的依赖项属性,然后直接与DataContext绑定即可。 As soon as the DataContext changes your bound object will reflect this change and therefore you can easily detect it and fire your own event.
一旦DataContext更改,您的绑定对象将反映此更改,因此您可以轻松地检测到它并触发您自己的事件。
public class MyControl : UserControl
{
public MyControl()
{
BindingOperations.SetBinding( this, MyControl.ObservedDataContextProperty, new Binding() );
}
public object ObservedDataContext
{
get { return (object) GetValue( ObservedDataContextProperty ); }
set { SetValue( ObservedDataContextProperty, value ); }
}
public static readonly DependencyProperty ObservedDataContextProperty =
DependencyProperty.Register( "ObservedDataContext", typeof( object ), typeof( MyControl ), new PropertyMetadata( null, OnObservedDataContextChanged ) );
private static void OnObservedDataContextChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
((MyControl) d).OnObservedDataContextChanged();
}
private void OnObservedDataContextChanged()
{
RaiseDataContextChanged();
}
private void RaiseDataContextChanged()
{
var h = DataContextChanged;
if (h != null) h( this, EventArgs.Empty );
}
public event EventHandler DataContextChanged;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.