以动态方式添加Click事件

时间:2016-05-31 09:57:59

标签: c# wpf

我正在尝试动态添加UI元素,但我遇到了问题,我能够添加UI元素,但我无法将Click事件添加到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

任何人都知道如何解决这个问题? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

由于错误消息指出要指定事件,您需要编译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;
}