如何从 xaml 传递参数?
我创建了自己的用户控件“ClockControl”,我通过主窗口的 XAML 对其进行初始化。
唯一的问题是我必须将参数传递给时钟控件的构造函数,但我不知道如何做到这一点。
如果我没有参数,这将有效:
<myControl:ClockControl></myControl:ClockControl>
但是我如何传递参数来执行此操作?
这是构造函数:
public ClockControl(String city)
{
InitializeComponent();
this.initController();
......
.....
}
提前致谢。
I have created my own UserControl "ClockControl", which I initialize through the main window's XAML.
The only problem is that I have to pass a parameter to the constructor of the clock control, and I have no clue of I how I can do that.
This works if I have no parameters:
<myControl:ClockControl></myControl:ClockControl>
But how can I pass a parameter doing this?
Here is the constructor:
public ClockControl(String city)
{
InitializeComponent();
this.initController();
......
.....
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的构造函数:
首先,如果您想从 XAML 使用
ClockControl
,那么您需要一个默认构造函数,即不带任何参数的构造函数。所以上面的构造函数是行不通的。我建议您定义一个名为
City
的属性,最好是依赖属性,然后从 XAML 使用它。像这样的东西:然后你可以在 XAML 中编写:
由于
City
是一个依赖属性,这意味着你甚至可以像这样进行Binding
:希望,这可以解决你的问题!
Your constructor:
First of all, if you want to use
ClockControl
from XAML, then you need a default constructor, means a constructor which doesn't take any parameter. So the above constructor is not going to work.I would suggest you to define a property with name
City
, preferably dependency property, and then use it from XAML. Something like this:Then you can write this in XAML:
Since
City
is a dependency property, that means you can even doBinding
like this:Hope, that solves your problem!
这是通过使用 DependencyProperty 来完成的,但不是通过构造函数。只需向控件本身添加属性并从代码隐藏中使用它们即可。
请阅读以下有关 DependencyProperty 的内容:
作为一个视觉注释,这将允许您执行以下操作,然后在隐藏代码:
This is done with the use of
DependencyProperty
's, however not via the constructor. Just by adding properties to the control itself and using them from the code-behind.Have a read of the following in regards to DependencyProperty's:
As a visual note, what this will allow you to do is the following, and then use it in the code-behind:
x:Arguments 指令 就是您所需要的。
x:Arguments directive would be what you need.
可以通过简单地绑定控件的 Tag 属性来简化此操作。快速而肮脏,也许不太优雅,但可以节省添加另一个属性的时间。
Could simplify this by simply binding the Tag property of the control. Quick and dirty, and perhaps not overly elegant, but saves times adding another property.