依赖项属性
[一篮饭特稀原创,转载请注明出处http://www.cnblogs.com/wanghafan/archive/2012/05/10/2493808.html]
在SL和WPF中定义依赖项属性来设定属性
系统中要实现设置IsTree为true,显示树状列表,否则显示下拉列表功能
App.xaml.cs代码:
View Code
1 private void Application_Startup(object sender, StartupEventArgs e) 2 { 3 //this.RootVisual = new MainPage(); 4 Strongsoft.Module.Contact.ContactTree uc = new Strongsoft.Module.Contact.ContactTree(); 5 uc.IsTree = false; 6 uc.ContactSelect += (ss, ee) => { MessageBox.Show(ee.ContactID + "|" + ee.ProfileID); }; 7 this.RootVisual = uc; 8 }
ContactTree.xaml.cs代码:
View Code
1 #region 依赖项属性 2 public static readonly DependencyProperty IsTreeProperty = 3 DependencyProperty.Register("IsTree", typeof(bool), 4 //IsTree是依赖项属性的名称,bool是类型 5 typeof(ContactTree), new PropertyMetadata(IsTreeChangedCallback)); 6 //ContactTree是依赖项属性的拥有者类型,IsTreeChangedCallback是回调函数 7 public bool IsTree 8 { 9 get { return (bool)GetValue(IsTreeProperty); } 10 set { SetValue(IsTreeProperty, value); } 11 } 12 private static readonly object synIsTreeChangedCallback = new object(); 13 //定义一个空对象来锁定依赖项的操作,避免一个操作未完成的时候另一个操作又出发使得依赖项的值发生变化 14 private static void IsTreeChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) 15 { 16 lock (synIsTreeChangedCallback) //锁定对象防止被改 17 { 18 if (sender != null && sender is ContactTree) 19 { 20 ContactTree owner = sender as ContactTree; 21 bool tree; 22 try 23 { 24 tree = (bool)e.NewValue; 25 } 26 catch 27 { 28 tree = true; 29 } 30 switch (tree) 31 { 32 case true: 33 owner.isTreeTrue(); 34 break; 35 case false: 36 owner.isTreeFalse(); 37 break; 38 } 39 } 40 } 41 } 42 private void isTreeTrue() 43 { 44 tvLeftOrgan.Visibility = Visibility.Visible; 45 cbContent.Visibility = Visibility.Collapsed; 46 btnShowHid.Visibility = Visibility.Collapsed; 47 tvLeftOrgan.Margin = new Thickness(0, 0, 0, 0); 48 } 49 private void isTreeFalse() 50 { 51 tvLeftOrgan.Visibility = Visibility.Collapsed; 52 cbContent.Visibility = Visibility.Visible; 53 btnShowHid.Visibility = Visibility.Visible; 54 tvLeftOrgan.Margin = new Thickness(0, 21, 0, 0); 55 } 56 #endregion