【问题标题】:XamlReader with Click Event带有点击事件的 XamlReader
【发布时间】:2011-12-29 10:18:01
【问题描述】:

我在我的 WPF 项目中使用 XamlReader。它可以工作 (My reference)

我当前的示例 Xaml 是这样的:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600">
  <Button Name="Test1" Content="Test1" Width="357" Height="88" Margin="14,417,0,0" ></Button>
  <Button Name="Test2" Content="Test2" Width="357" Height="88" Margin="14,529,0,0" ></Button>
</Grid>

并像这样添加按钮的点击事件:

button = LogicalTreeHelper.FindLogicalNode(rootObject, "Test1") as Button ;
button.Click += new RoutedEventHandler(Button1_Click);

可以这样写xaml吗?

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600">
  <Button Name="Test1" Content="Test1" ... Click="Button1_Click"></Button>
  <Button Name="Test2" Content="Test2" ... Click="Button2_Click"></Button>
</Grid>

【问题讨论】:

    标签: wpf xaml xamlreader


    【解决方案1】:

    XamlReader.Load 不允许在其中附加eventHandlers。所以使用这种技术将eventHandlers动态附加到它。

    1- 编写不带eventHandlers 的 Xaml 字符串 - 但编写这些控件的 Name 属性。

    2- 用XamlReader.Load(str);加载字符串

    3- 然后从中加载 DataTemplate 的内容。使用Grid template = ((Grid)(dt.LoadContent()));

    注意:这里GridDataTemplate中的父控件。

    4- 按名称查找要附加事件处理程序的控件。 Button img = (Button)template.FindName("MyButtonInDataTemplate");

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      没有。您无法使用原始 XAML 在运行时保存或加载事件。这是 XAML 序列化的限制,因为序列化的 XAML 是自包含的,这意味着每个资源都应该在原始 XAML 中加载,而事件的代码逻辑不是。阅读更多here

      【讨论】:

      • 谢谢 Neeraj。我想,我也不能添加 Template 属性。
      猜你喜欢
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 2016-03-07
      • 2014-09-04
      • 1970-01-01
      相关资源
      最近更新 更多