【问题标题】:How can you access the Control within a ControlTemplate in Silverlight?如何在 Silverlight 的 ControlTemplate 中访问控件?
【发布时间】:2012-01-11 14:49:11
【问题描述】:

我有以下代码:

ControlTemplate ct = (ControlTemplate)XamlReader.Load(validXmlString);

现在我需要获取这个模板创建的控件,在我的例子中是一个按钮。我进行了广泛的搜索,但找不到一个简单的解释来说明这是如何完成的。

请注意,由于某些无法解释的原因,Microsoft 在 WPF 中为 ControlTemplate 提供了 FindControl() 方法,但在 Silverlight 中没有。我已经读过这可以通过 VisualTreeHelper 来完成,但我还没有看到关于如何做的解释。

【问题讨论】:

  • 你真的不应该那样做......
  • 无益的回应,Silverlight 在其 DataGrid 的实现中存在严重缺陷,我只能别无选择这样做。你知道如何做到这一点吗?如果有,请分享。
  • 别无选择?也许你忽略了一些东西,你到底想达到什么总体目标?

标签: wpf silverlight silverlight-4.0 wpf-controls silverlight-3.0


【解决方案1】:

您将在下面找到一个示例,该示例递归地遍历可视树并找到将所有按钮添加到集合中。您可以检查按钮的名称等......并做您需要做的事情。我只是以一个集合为例,因为我在上面找到了一个快速示例。

public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        List<UIElement> buttons = new List<UIElement>();

        GetChildren(this, typeof(Button), ref buttons);
    }

    private void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children)
    {
        int count = VisualTreeHelper.GetChildrenCount(parent);
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
                if (child.GetType() == targetType)
                {
                    //DO something with the button in the example added to a collection. You can also verify the name and perform the action you wish.
                    children.Add(child);
                }
                GetChildren(child, targetType, ref children);
            }
        }
    }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2010-10-23
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多