我正在创建一个带有依赖项属性的自定义控件,我希望将自定义类绑定到该属性。当属性得到更新时,我想调用一个方法,以便它可以重新配置控件......我迷路了。
internal partial class CollectionScheduleDayView : Canvas
{
public static DependencyProperty AppointmentsCollectionProperty = DependencyProperty.Register( "Collection", typeof( AppointmentCollections ), typeof( CollectionScheduleDayView ), new PropertyMetadata( null, PropertyChangedCallback ) );
private static void PropertyChangedCallback( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e )
{
SetDataContext( dependencyObject, e );
}
public AppointmentCollections Collection
{
get
{
return GetValue( AppointmentsCollectionProperty ) as AppointmentCollections;
}
set
{
SetValue( AppointmentsCollectionProperty, value );
}
}
public CollectionScheduleDayView()
{
InitializeComponent();
}
void CollectionScheduleDayView_DataContextChanged( object sender, DependencyPropertyChangedEventArgs e )
{
}
private static void SetDataContext( DependencyObject control, DependencyPropertyChangedEventArgs e )
{
var dayView = control as CollectionScheduleDayView;
if (e.NewValue != null)
{
if (dayView != null)
{
dayView.Collection = e.NewValue as AppointmentCollections;
dayView.DataContext = dayView.Collection;
dayView.SetupControl();
}
}
}
public void SetupControl()
{
ResetControl();
Collection.RescheduledAppointments.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( RescheduledAppointments_CollectionChanged );
Collection.CompletedAppointments.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( CompletedAppointments_CollectionChanged );
Collection.RemainingAppointments.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( RemainingAppointments_CollectionChanged );
if (Collection.RescheduledAppointments == null || Collection.RescheduledAppointments.Count == 0)
{
CollapseRescheduled();
}
if (Collection.CompletedAppointments == null ||Collection.CompletedAppointments.Count == 0)
{
CollapseCompleted();
}
}
//...some other code below
}
我绑定到我的财产就好了:
<my:CollectionScheduleDayView Grid.Column="0" HorizontalAlignment="Left" Margin="12,35,0,0" x:Name="DayView0" VerticalAlignment="Top" Collection="{Binding DayOneAppointmentCollections, NotifyOnSourceUpdated=True}" SourceUpdated="CollectionScheduleDayView1_OnSourceUpdated"/>
PropertyChangedCallback
只被调用一次,从不再次调用该方法来更新控件;然而,绑定正在更新,当源更新时,属性会更新...也不会在我的viewmodel中调用onpropertychanged()。
当我通过重新实例化绑定到我的控件的对象强制在我的viewmodel中调用onpropertychanged()时 - 绑定工作一次,但即使调用了onpropertychanged(),它也不会在属性更改时更新。
我怎么知道绑定更新的时间?我的dependencyproperty代码是否正确?
答案 0 :(得分:0)
有一些事情对我来说是错误的。
1这不是必需的,因为绑定会为您做到这一点。如果你在这里放一个断点,你应该看到dayView.Collection和e.NewValue已经相同了。
dayView.Collection = e.NewValue as AppointmentCollections;
2这也不是必需的。我认为这可能是主要的罪魁祸首,因为您将DataContext更改为“DayOneAppointmentCollections”不再存在的位置。
dayView.DataContext = dayView.Collection;
3在SetupControl中,请务必取消订阅旧收藏。