使用WPF中的附加特性

本文关键字:WPF 使用 | 更新日期: 2023-09-27 18:24:52

我正试图在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甚至没有被击中。

哦,这是我的第一个问题,希望我足够清楚

使用WPF中的附加特性

你可以这样尝试

附加属性

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>

希望它能有所帮助!