WPF 自定义属性
WPF 自定義屬性 原文:WPF 自定義屬性
? 做了一個自定義控件和一個自定義Grid,里面的元素可以隨著綁定屬性變化:
效果圖(一定滑塊):
關(guān)鍵代碼:
1、自定義屬性代碼:
public class MyGrid : Grid{public static readonly DependencyProperty ColumnCountProperty = DependencyProperty.Register("ColumnCount", typeof(int), typeof(MyGrid),new FrameworkPropertyMetadata((int)1,FrameworkPropertyMetadataOptions.AffectsRender,null,new CoerceValueCallback(CoerceColumnCount)));public int ColumnCount{get { return (int)GetValue(ColumnCountProperty); }set { SetValue(ColumnCountProperty, value); }}private static object CoerceColumnCount(DependencyObject element, object value){int input = (int)value;if (input < 1){return 1;}else{return input;}}protected override void OnRender(System.Windows.Media.DrawingContext dc){base.OnRender(dc);//獲得現(xiàn)有行數(shù)、列數(shù)int columnCount = this.ColumnDefinitions.Count;int rowCount = this.RowDefinitions.Count;//不變化,則不處理if (this.ColumnDefinitions.Count == this.ColumnCount) return;//獲得最后一個元素的數(shù)量int elementCount = 0;for (int i = this.Children.Count - 1; i >= 0; i--){UIElement element = this.Children[i];int row = Grid.GetRow(element);int column = Grid.GetColumn(element);int num = row * columnCount + column + 1;if (num > elementCount){elementCount = num;}}//大于最大數(shù),直接返回if (this.ColumnCount > elementCount) return;//計算新行列int newRowCount = (int)Math.Ceiling((double)elementCount / this.ColumnCount);int newColumnCount = this.ColumnCount;this.RowDefinitions.Clear();this.ColumnDefinitions.Clear();for (int i = 0; i < newRowCount; i++){RowDefinition rd = new RowDefinition();this.RowDefinitions.Add(rd);}for (int i = 0; i < newColumnCount; i++){ColumnDefinition cd = new ColumnDefinition();this.ColumnDefinitions.Add(cd);}//添加元素foreach (UIElement element in this.Children){int row = Grid.GetRow(element);int column = Grid.GetColumn(element);int allCount = row * columnCount + column;int newRow = allCount / newColumnCount;int newColumn = allCount % newColumnCount;Grid.SetRow(element, newRow);Grid.SetColumn(element, newColumn);}}}里面有兩個地方需要注意:
1、依賴屬性一定要設(shè)定為?static ,要不然在XAML中引用的時候出現(xiàn)異常,VS直接卡死;
2、在OnRender函數(shù)中,一定要盡量少的執(zhí)行代碼,因為這個方法一直在異步刷新;
用到的算法:
進(jìn)制的轉(zhuǎn)化思想:先計算出一種進(jìn)制的十進(jìn)制,再轉(zhuǎn)換為別的進(jìn)制。
?
例子下載:Code
posted on 2019-04-15 10:07 NET未來之路 閱讀(...) 評論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/lonelyxmas/p/10709034.html
總結(jié)
- 上一篇: 04.ARP:地址解析协议
- 下一篇: 七、Oracle 数据库设计