Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c# - How do you pass parameters from 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?

Here is the constructor:

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

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your constructor:

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

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:

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();
        }
        //..........
}

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...