日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

WPF 自定义属性

發布時間:2025/7/25 124 豆豆
生活随笔 收集整理的這篇文章主要介紹了 WPF 自定义属性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
WPF 自定義屬性 原文:WPF 自定義屬性

? 做了一個自定義控件和一個自定義Grid,里面的元素可以隨著綁定屬性變化:

效果圖(一定滑塊):

關鍵代碼:

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);//獲得現有行數、列數int columnCount = this.ColumnDefinitions.Count;int rowCount = this.RowDefinitions.Count;//不變化,則不處理if (this.ColumnDefinitions.Count == this.ColumnCount) return;//獲得最后一個元素的數量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;}}//大于最大數,直接返回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、依賴屬性一定要設定為?static ,要不然在XAML中引用的時候出現異常,VS直接卡死;

2、在OnRender函數中,一定要盡量少的執行代碼,因為這個方法一直在異步刷新;

用到的算法:

進制的轉化思想:先計算出一種進制的十進制,再轉換為別的進制。

?

例子下載:Code

posted on 2019-04-15 10:07 NET未來之路 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/lonelyxmas/p/10709034.html

總結

以上是生活随笔為你收集整理的WPF 自定义属性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。