在XAML中,如何使用DependencyProperty向按钮添加命令? [英] In XAML, how do I add a command to a button using DependencyProperty?

查看:65
本文介绍了在XAML中,如何使用DependencyProperty向按钮添加命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在努力学习一些XAML语法。在第一段代码中,我将命令附加到按钮属性中的按钮:



Hi,

I'm struggling with some XAML syntax. In this first piece of code, I have attached a command to a button in the button's attributes:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class="MyAssembly.CodeBehindClass">

	<StackLayout>
		<Button x:Name="buttonName" Text="Press" Command="{Binding ButtonOnClickedCommand}" />
	</StackLayout>

</ContentPage>





这很好用。但是如果我想使用如下所示的替代语法呢?我可以设置文本没问题,但我无法弄清楚如何绑定命令:





This works fine. But what if I want to use the alternative syntax as shown below? I can set the text no problem, but I can't figure out how to bind the command:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class="MyAssembly.CodeBehindClass">

	<StackLayout>
		<Button x:Name="buttonName">
            <Button.Text>Press</Button.Text>
            <Button.Command>STRUGGLING FOR SYNTAX HERE</Button.Command>
	</StackLayout>

</ContentPage>





我想我可以更简单地表达我的问题如下:



通常,在XAML中,如果你有一个带有属性的UI元素,那么你可以用两种方式设置属性。你可以这样做:





I think I can express my question more simply as follows:

In general, in XAML, if you have a UI element with a property then you can set the property one of two ways. You can either do this:

<MyControl MyProperty="Value-which-may-be-a-binding-expression"/>





或者你可以完成同样的事情:< br $> b $ b



Or you can achieve exactly the same thing like this:

<MyControl>
    <MyControl.MyProperty>Value-goes-here</MyControl.MyProperty>
</MyControl>





我可以使用各种属性来解决这个问题,但是无法通过命令来解决这个问题。但我认为我的问题不是具体的 Command 属性;我认为这是事实,我不知道如何使用上面的第二种语法编写绑定表达式。



希望这是有道理的。







亲切的愿望~Patrick



I can get this to work with various properties but can't work out how to do it with the Command. But I think my problem is not specifically the Command property; I think it is the fact that I don't know how to write a binding expression using the second syntax above.

Hope this makes sense.



Kind wishes ~ Patrick

推荐答案

你刚才需要添加一个 Binding 元素,其元素与 {Binding ...} 标记扩展名相同:

You just need to add a Binding element, with the same properties as the {Binding ...} markup extension:
<Button x:Name="buttonName">
    <Button.Text>Press</Button.Text>
    <Button.Command>
        <Binding Path="ButtonRelaxOnClickedCommand" />
    </Button.Command>
</Button>



属性元素语法:XAML语法详细信息 [ ^ ]

在XAML中声明绑定:绑定声明概述 [ ^ ]


这篇关于在XAML中,如何使用DependencyProperty向按钮添加命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆