Установить событие на кнопку при создании через строку XAML - PullRequest
0 голосов
/ 05 июля 2018

Я получил следующий код, который будет динамически генерируемой сеткой:

string xaml = "<Grid Margin='8 8 0 0' Width='175'>" +
                "<Grid.RowDefinitions>" +
                    "<RowDefinition Height='115'/>" +
                    "<RowDefinition Height='*'/>" +
                    "<RowDefinition Height='Auto'/>" +
                "</Grid.RowDefinitions>" +
                "<Image Source='C:/Users/SaFteiNZz/Curro/yo2.png' Height='115' Width='171' Stretch='Uniform'/>" +
                "<Button x:Name='BtnEditAc' Grid.Row='0' Style='{StaticResource MaterialDesignFloatingActionMiniAccentButton}' HorizontalAlignment='Right' VerticalAlignment='Bottom' Margin='0,0,16,-20'>" +
                    "<materialDesign:PackIcon Kind='AccountSettingsVariant' Width='30' Height='30' Margin='0,0,0,5'/>" +
                "</Button>" +
                "<StackPanel Grid.Row='1' Margin='8,24,8,8'>" +
                    "<TextBlock TextWrapping='Wrap' FontWeight='Bold'>Pablo Antonio Hernandez Hernandez</TextBlock>" +
                    "<TextBlock TextWrapping='Wrap' VerticalAlignment='Center'>46080696N</TextBlock>" +
                "</StackPanel>" +
                "<Border BorderBrush='White' BorderThickness='1' CornerRadius='0' Grid.Row='0' Grid.RowSpan='3'>" +
                    "<Border.Effect>" +
                        "<DropShadowEffect BlurRadius='10' Direction='-90' Color='Black' ShadowDepth='0'/>" +
                    "</Border.Effect>" +
                "</Border>" +
            "</Grid>";

UIElement element = (UIElement)XamlReader.Parse(xaml, context);
empDisplay.Children.Add(element);

Как будто код работает.

Но я хочу установить событие клика для кнопки ( BtnEditAc ) , которое, если я сделаю это непосредственно в строке XAML, выдаст ошибку (Couldn ' создать клик из текста BtnEditAc_Click или что-то в этом роде).


Есть ли способ установить событие нажатия для этой кнопки? или подключиться к функции как-нибудь?

Я собираюсь сделать это, используя объекты CLR, кодированные вместо XamlReader, но сначала я хочу узнать, есть ли решение для этого.

Надеюсь, вы знаете, что я делаю не так.

Ответы [ 2 ]

0 голосов
/ 05 июля 2018

Вы можете анализировать привязку команд из xml вместо событий Click:

<Button x:Name='BtnEditAc' Command='{Binding MyCommand}' Grid.Row='0' ...

Если по какой-то причине вы не хотите использовать команды, вы можете вручную добавить событие щелчка в коде, если только вы можете найти Button в элементе xaml, который вы только что проанализировали. Например, если вы знаете, что корневым элементом в вашем сериализованном xaml будет Grid:

Grid rootElement = (Grid)XamlReader.Parse(xaml, context);
grdMain.Children.Add(rootElement);
Button btn = (Button)rootElement.FindName("BtnEditAc");
btn.Click += btn_Click;

Или:

UIElement elem = (UIElement)XamlReader.Parse(xaml, context);
Button b =(Button) LogicalTreeHelper.FindLogicalNode(elem, "BtnEditAc");

В качестве альтернативы, если вы не знаете тип корневого элемента, вы можете использовать этот код , чтобы найти его по имени и типу:

    public static T FindChild<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++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            T childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<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;
                }
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

или, если вы не знаете имя своей кнопки, вы можете, например, получить первый дочерний элемент типа Button (или реализовать метод, который будет возвращать все дочерние элементы данного типа) с помощью этого метода расширения

    public static T GetChildOfType<T>(this DependencyObject depObj) where T : DependencyObject
    {
        if (depObj == null) return null;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);

            var result = (child as T) ?? GetChildOfType<T>(child);
            if (result != null) return result;
        }
        return null;
    }

Если вы хотите установить обработчик событий в xaml и разобрать его вручную, я не знаю, можно ли это сделать.

0 голосов
/ 05 июля 2018

Давайте посмотрим, может ли это решение работать:

//Here you have the grid
Grid element = (Grid)XamlReader.Parse(xaml, context);
//Now try to get the button
Button btn = (Button)element.FindName("BtnEditAc");
if(btn != null)
{
    btn.Click  += new RoutedEventHandler(OnBtnEditAcClick);
}

Где OnBtnEditAcClick - обработчик событий. Затем добавьте элемент в ваш основной вид:

empDisplay.Children.Add(element);

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...