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

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

问题描述

我创建了自己的 UserControlClockControl",我通过主窗口的 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();
    //...
}

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

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.

我建议您定义一个名为 City 的属性,最好是依赖属性,然后从 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" />

由于 City 是一个依赖属性,这意味着你甚至可以像这样进行 Binding :

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天全站免登陆