有没有办法从xaml调用外部函数?
有没有办法直接从xaml调用外部对象(例如资源对象)的方法?
我的意思是这样的:
<Grid xmlns:dm="clr-namespace:MyNameSpace;assembly=MyAssembly">
<Grid.Resources>
<dm:TimeSource x:Key="timesource1"/>
</Grid.Resources>
<Button Click="timesource_updade">Update time</Button>
</Grid>
timesource_update 方法当然是 TimeSource 对象的方法。
我需要使用纯 XAML,而不是任何隐藏的代码。
Is there any way to call methods of external objects (for example resource objects) directly from xaml?
I mean something like this:
<Grid xmlns:dm="clr-namespace:MyNameSpace;assembly=MyAssembly">
<Grid.Resources>
<dm:TimeSource x:Key="timesource1"/>
</Grid.Resources>
<Button Click="timesource_updade">Update time</Button>
</Grid>
The method timesource_update is of course the method of the TimeSource object.
I need to use pure XAML, not any code behind.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查这个线程,它有类似的问题。一般来说,您不能直接从 xaml 调用方法。
您可以使用命令,也可以从 xaml 创建一个对象,该对象将在线程上创建一个方法,该方法将在需要时自行处置。
但恐怕你无法仅用纯 XAML 来做到这一点。在 C# 中,您可以执行 XAML 中可以执行的所有操作,但反之则不然。您只能从 XAML 执行一些在 C# 中可以执行的操作。
Check this thread, it has a similar problem. In general you can't call a method directly from xaml.
You could use Commands or you can create an object from xaml which will create a method on a thread, which will dispose itself when it needs.
But I am afraid you can't do it just in pure XAML. In C# you can do everything you can do in XAML, but not other way round. You can only do some certain things from XAML that you can do in C#.
好的,这是最终的解决方案。
XAML:
TimeSource 类中的代码:
TimeSource 必须从 UIElement 派生才能拥有 CommandBindings。但结果是直接从 XAML 调用外部程序集方法。通过单击该按钮,将调用对象 timesource1 的“UpdateExecuted”方法,这正是我正在寻找的。
OK, here is the final sollution.
XAML:
CODE in the TimeSource class:
TimeSource has to be derived from UIElement in order to have CommandBindings. But the result is calling outer assembly method directly from XAML. By clicking the button, 'UpdateExecuted' method of the object timesource1 is called and that is exactly what I was looking for.