如何将单击事件处理程序添加到TextBox的DeleteButton?

时间:2015-07-07 09:58:31

标签: winrt-xaml

我的一个Windows运行时应用程序页面中有一个TextBox。当TextBox中有文本时,它会显示一个黑色十字,当单击它时,它会清除TextBox。显然这是默认模板中的DeleteButton,关于如何删除它有很多关于SO的问题。我不想删除它,但我确实想添加一个事件处理程序,所以我知道它何时被单击。

如何将单击事件处理程序添加到TextBox的DeleteButton?我更喜欢一个能让我不得不复制模板的答案。

1 个答案:

答案 0 :(得分:1)

<TextBox x:Name="TestTextBox" Loaded="TestTextBox_Loaded" Width="300" Height="100"></TextBox>

最简单的方法是使用WinRTXamlToolkit中的VisualTreeHelperExtension(或NuGet package)。

使用TreeHelper,您可以轻松访问按钮:

    private void TestTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        var deleteButton = TestTextBox.GetChildByName<Button>("DeleteButton");
        deleteButton.Click += deleteButton_Click;
    }

    void deleteButton_Click(object sender, RoutedEventArgs e)
    {
        throw new NotImplementedException();
    }

我使用这个功能:

    public static T GetChildByName<T>(this DependencyObject parent, string childName) where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null) { return null; }

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            var childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = GetChildByName<T>(child, childName);

                // If the child is found, break so we do not overwrite the found child. 
                if (foundChild != null) { break; }
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name
                    foundChild = (T)child;
                    break;
                }

                // Need this in case the element we want is nested
                // in another element of the same type
                foundChild = GetChildByName<T>(child, childName);
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }
        return foundChild;
    }