[英]Using attached properties in WPF
我試圖在WPF中創建一個只讀附加屬性,該屬性將計算控件的總Visual Child計數。 這樣做的好處對我而言並不重要,因為它能夠正確使用附加屬性!
首先,我這樣聲明我的財產:
internal static readonly DependencyPropertyKey TotalChildCountPropertyKey =
DependencyProperty.RegisterAttachedReadOnly("TotalChildCount", typeof(int), typeof(MyAttachClass), new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty TotalChildCountProperty = TotalChildCountPropertyKey.DependencyProperty;
public static int GetTotalChildCount(DependencyObject obj)
{
return (int)obj.GetValue(TotalChildCountProperty);
}
public static void SetTotalChildCount(DependencyObject obj, int value)
{
obj.SetValue(TotalChildCountPropertyKey, value);
}
我還有一個聲明為其他方式的遞歸方法,如下所示:
public static class Recursive
{
public static IEnumerable<DependencyObject> GetAllChildren(DependencyObject obj)
{
List<DependencyObject> col = new List<DependencyObject>();
GetAllChildrenImp(obj, col);
return col;
}
private static void GetAllChildrenImp(DependencyObject current, List<DependencyObject> col)
{
if (current != null)
{
col.Add(current);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++ )
{
GetAllChildrenImp(VisualTreeHelper.GetChild(current, i), col);
}
}
}
}
現在,我希望使用此方法為GetTotalChildCount屬性分配一個值,但是我無法找出最好的方法。 我可以向依賴項屬性更改中添加事件處理程序,但這將永遠不會觸發,因為我只會從xaml中的值中進行讀取。
這是我在xaml中使用它的方式:
<TextBox DataContext="{RelativeSource Self}" Text="{Binding local:MyAttachClass.TotalChildCount}"></TextBox>
總結一下。 我希望設置一個DependencyObjects TotalChildCount附加屬性,然后能夠在xaml中將其綁定。 從目前的情況來看,這是行不通的,GetTotalChildCount甚至沒有被擊中。
哦,這是我的第一個問題,希望我已經足夠清楚了
你可以這樣嘗試
附屬財產
public class MyAttachClass
{
public static readonly DependencyProperty TotalChildCountProperty = DependencyProperty.RegisterAttached("TotalChildCount", typeof(int), typeof(MyAttachClass),
new PropertyMetadata(-1, OnTotalChildCountChanged));
public static int GetTotalChildCount(DependencyObject obj)
{
return (int)obj.GetValue(TotalChildCountProperty);
}
public static void SetTotalChildCount(DependencyObject obj, int value)
{
obj.SetValue(TotalChildCountProperty, value);
}
public static void OnTotalChildCountChanged(object sender, DependencyPropertyChangedEventArgs e)
{
TextBox txt = sender as TextBox;
if (txt != null)
{
var children = Recursive.GetAllChildren(txt);
txt.Text = children.Count().ToString();
}
}
}
和xaml為
<TextBox local:MyAttachClass.TotalChildCount="0" ></TextBox>
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.