我正在尝试在WPF中创建一个只读附加属性,该属性将计算控件的总可视子项数。这样做的好处对我来说并不重要,它能够正确使用附加属性!
首先,我已经宣布我的财产如此:
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);
}
}
}
}
我还有一个递归方法,在其他地方声明:
<TextBox DataContext="{RelativeSource Self}" Text="{Binding local:MyAttachClass.TotalChildCount}"></TextBox>
现在我希望使用此方法为GetTotalChildCount属性赋值,但我无法找出最佳方法。我可以为依赖项属性更改添加一个事件处理程序,但这永远不会触发,因为我只会读取xaml中的值。
以下是我在xaml中使用它的方法:
DbGeography
总结一下。我希望设置DependencyObjects TotalChildCount附加属性,然后能够在xaml中绑定它。目前这不起作用,GetTotalChildCount甚至没有被击中。
哦,这是我的第一个问题,希望我很清楚
答案 0 :(得分:-2)
你可以这样试试
附属物
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>
希望它有所帮助!