WPF Events

在学习http://msdn.microsoft.com/en-us/library/ms771766.aspx 这个例子的时候,遇到了这样的问题。想通了以后就很简单,但是还是让我抓耳挠腮了很久时间。呵呵。

 

问题是这样的,我想用DependencyPropety来描绘这个控件,如果这个Property变化的话,就重新UpateLayout. 实现非常简单:

  1. 注册DependecnyProperty

代码如下:

 

代码
1         public Size PuzzleSize
2         {
3             get { return (Size)this.GetValue(PuzzleSizeProperty); }
4             set { this.SetValue(PuzzleSizeProperty, value); }
5         }
6         public static readonly DependencyProperty PuzzleSizeProperty = DependencyProperty.Register(
7           "PuzzleSize"typeof(Size), typeof(PuzzleControl),
8           new FrameworkPropertyMetadata(new PropertyChangedCallback(OnPuzzleSizeChangedCallback)));

 

 

  1. 注册事件处理信息

 

代码
      private static void OnPuzzleSizeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            RoutedEventArgs newargs 
= new RoutedEventArgs(SizeChangedEvent);
            (d 
as FrameworkElement).RaiseEvent(newargs);
        }

        
private void OnPuzzelEventChanged(object sender, RoutedEventArgs e)
        {
            ConstructLayout();
        }

 

问题是,在ConstructLayout的时候,必须要动态的生成一些VisualElments,然后这些VisualElment可以Apply固定的Style,并且把这些Style服之。

这个需求看起来十分的普通。但是却纠缠了我很久...

 

因为在这样的机制下,VisualElment Tempalte里面的VisualTree,永远是空的。

 

那么好吧,我换一个地方,例如Loaded事件。发现还是不行。到后来用了法宝ApplyTemplate才把这一关给绕过去。查了一些解释, 例如,http://blogs.msdn.com/silverlight_sdk/archive/2008/10/24/loaded-event-timing-in-silverlight.aspx 和http://blogs.msdn.com/devdave/archive/2008/10/11/control-lifecycle.aspx

 

里面提到,In the Measure pass of layout. The Template property will be applied if the control has no visual tree. The control starts life with no visual tree, and the visual tree will be cleared when the Template property is set. You can also call ApplyTemplate yourself.

 

posted @ 2009-12-08 16:21  Pang pang Xiong  阅读(232)  评论(0编辑  收藏  举报