How do you pass parameters from xaml?

后端 未结 4 1456
我寻月下人不归
我寻月下人不归 2020-12-01 03:38

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 co

相关标签:
4条回答
  • 2020-12-01 04:08

    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.

    0 讨论(0)
  • 2020-12-01 04:14

    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!

    0 讨论(0)
  • 2020-12-01 04:18

    x:Arguments directive would be what you need.

    0 讨论(0)
  • 2020-12-01 04:25

    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:

    • Dependency Properties Overview
    • DependencyProperty Class MSDN
    • Why Dependency Properties?

    As a visual note, what this will allow you to do is the following, and then use it in the code-behind:

    <myControl:ClockControl City="New York"></myControl:ClockControl>
    
    0 讨论(0)
提交回复
热议问题