【问题标题】:Attach to a click event in XAML control when loading XAML dynamically.动态加载 XAML 时附加到 XAML 控件中的单击事件。
【发布时间】:2016-06-23 16:51:24
【问题描述】:

我有一个在运行时动态加载的 XAML 控件。这是纯 XAML,没有后面的代码。

我无法控制父加载机制,这就是为什么这看起来有点奇怪。

我有一个父应用程序,它加载我的插件 DLL 并加载我的 XAML 控件。

我的 DLL 签名是:

public class Application : BaseClassHere
{
    public Application(IParentContext context) : base(context)
    {
        // Im placing this instance in the bag which i use in my XAML
        base.MyObservablePropertyBag["MyParentContext"] = new ObservableValue<object>(this);
    }
}

我的 XAML 是这样的:

<av:UserControl 
    xmlns:local="clr-namespace:MyApplicationNS;assembly=MyDll"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" >

    <Border DataContext="{Binding MyObservablePropertyBag[MyParentContext].Value}" >

        <Button Name="MyButton" />

    </Border>
</UserControl>

此绑定在 XAML 中完美运行。我可以完全访问我在 Application 类中定义的所有公共属性。

我的问题是我想链接到我的按钮上的点击事件。如果我在 XAML 中添加一个 Click 事件,它会在运行时出错,告诉我我需要编译我的 XAML。

有没有办法订阅Application类中MyButton的Click事件?

【问题讨论】:

  • 通过 xaml 向 Routed.Event click 添加事件触发器时出错?

标签: c# wpf xaml events runtime


【解决方案1】:

好吧,如果您说绑定有效,那么为什么要尝试弄乱 Click 事件呢?而是使用 Button 的 Command 属性。创建一个ICommand 实例(如DelegateCommandRelayCommand),将其放入您的propertybag 并绑定到它!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2023-03-27
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多