[英]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.