c# - 动态添加点击事件

标签 c# wpf

我正在尝试动态添加 UI 元素,但我遇到了一个问题,我可以添加 UI 元素,但我无法将点击事件添加到 Button

下面是我的代码:

ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");

string xaml = String.Format(" <StackPanel Orientation='Vertical'>");
xaml = xaml + "<StackPanel Orientation='Horizontal'>";
xaml = xaml + "<Button Margin='5,5,0,0'  Background='AliceBlue' Foreground='DarkBlue' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='82'  Tag='12' Click='btnMy_Click'>";
xaml = xaml + "<StackPanel Orientation='Horizontal'>";
xaml = xaml + "<Image Source='/MotionTest;component/images/open.png' Width='18' Height='18' />";
xaml = xaml + "<TextBlock Text='  Open' VerticalAlignment='Center' FontSize='13' />";
xaml = xaml + "</StackPanel>";
xaml = xaml + "</Button>";
xaml = xaml + "</StackPanel>";
xaml = xaml + "</StackPanel>";

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

还有我的 onClick 函数:

private void btnMy_Click(object sender, RoutedEventArgs e)
{
    var myValue = ((Button)sender).Tag;
    MessageBox.Show("Here = " + myValue);
}

对于这一行:

 xaml = xaml + "<Button Margin='5,5,0,0'  Background='AliceBlue' Foreground='DarkBlue' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='82'  Tag='12' Click='btnMy_Click'>";

如果我删除

Click='btnMy_Click'

它会起作用的。但是如果我添加它,它会显示

enter image description here

有人知道怎么解决吗? 提前致谢。

最佳答案

由于错误消息指出要指定事件,您需要编译 XAML 文件,而您明确不想这样做,这似乎是不切实际的(您可以编译一个临时程序集并加载它,但是你不能再次卸载它)。

你可以做的是给元素一个名字:

xaml = xaml + "<Button x:Name='ClickMe'>";

然后,使用辅助函数来检索它:

var button = UIHelper.FindChild<Button>(element, "ClickMe");
button.Click += btnMy_Click;

辅助函数看起来像这样,我从How can I find WPF controls by name or type? :

/// <summary>
/// Finds a Child of a given item in the visual tree. 
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter. 
/// If not matching item can be found, 
/// a null parent is being returned.</returns>
public static T FindChild<T>(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;
}

关于c# - 动态添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37542523/

相关文章:

c# - Twilio API 的forceDelivery 标志到底有什么作用?

c# - 如何在视频控件上方添加透明控件,如 mediaelement 上的 wpf 标签

c# - 非 Web 项目的 XML 序列化程序集

c# - 从 View 获取 List<ViewModel> 到 Controller

c# - 如何在所有音频设备上播放声音

c# - C#中的ConfigurationManager有什么问题吗?

c# - CrossThreadMessagingException WPF OpenFileDialog

c# - 基于对象集合的动态ContextMenu的模式/方法

wpf - 当命令 CanExecute 为 false 时,按钮不会被禁用

wpf - 从主窗口访问 ICommand : Josh Smith's Article