如何传递从XAML参数? [英] How do you pass parameters from xaml?

查看:205
本文介绍了如何传递从XAML参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了自己的用户控件ClockControl,这是我通过主窗口的XAML初始化。

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?

下面是构造函数:

public ClockControl(String city)
    {
        InitializeComponent();
        this.initController();
        ......
        .....
    }

先谢谢了。

推荐答案

您的构造函数:

public ClockControl(String city)
{
    InitializeComponent();
    this.initController();
    //...
}

首先,如果你想使用 ClockControl 从XAML,那么你需要一个默认的构造函数,是指一个构造函数,不带任何参数。所以上面的构造函数行不通的。

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.

我建议你定义一个名称的属性城市,preferably依赖属性,然后用它从XAML。事情是这样的:

I would suggest you to define a property with name City, preferably dependency property, and then use it from XAML. Something like this:

public class ClockControl: UserControl
    {
        public static readonly DependencyProperty CityProperty = DependencyProperty.Register
            (
                 "City", 
                 typeof(string), 
                 typeof(ClockControl), 
                 new PropertyMetadata(string.Empty)
            );

        public string City
        {
            get { return (string)GetValue(CityProperty); }
            set { SetValue(CityProperty, value); }
        }

        public ClockControl()
        {
            InitializeComponent();
        }
        //..........
}

然后就可以在XAML中这样写:

Then you can write this in XAML:

<myControl:ClockControl City="Hyderabad" />

由于城市是一个依赖属性,这意味着你甚至可以做绑定是这样的:

Since City is a dependency property, that means you can even do Binding like this:

<myControl:ClockControl City="{Binding Location}" />

希望,解决您的问题!

Hope, that solves your problem!

这篇关于如何传递从XAML参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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