how to pass parameter in wpf control constructor?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I have written my control and trying to pass parameter for additional initialization but there are errors =( (tHE TYPE Ajustcontrol could not have a name attribut ). How to pass data correctly? this is my code in c#:

public AjustControl(BaoC input)         {             InitializeComponent();              populateAdjustControl(input);          } 

Error:Error 15 The type 'AjustControl' cannot have a Name attribute. Value types and types without a default constructor can be used as items within a ResourceDictionary. Line 470 Position 26. D:\Prj\aaa\MainWindow.xaml 470 26 Studio

回答1:

So, as the error says. You cannot have controls without parameterless constructor in xaml. You can still add one if you want to instantiate it from code, but xaml won't call that constructor.

public AjustControl(BaoC input) : this() {     populateAdjustControl(input); }  public AjustControl() {     InitializeComponent(); } 

However, if you are asking to add custom property to your control, you can add a DependancyProperty.

public static readonly DependencyProperty NameProperty=      DependencyProperty.Register(     "Name", typeof(string), ...     ); public string Name {     get { return (string)GetValue(NameProperty); }     set { SetValue(NameProperty, value); } } 

After this, you can use your control like

<custom:AjustControl Name="something" /> 


回答2:

It is not clear from your question why you need to pass the parameter to the constructor of the custom control.

  1. It may be because you need the custom control to consume the offending parameter before any bound values are passed from custom control to parent via dependency property mechanisms - most notably bound properties that would consume the offending constructor parameter directly or indirectly.

  2. It may be because initialization via parameterized constructor is the only way to go for you for whatever reasons.

I don't know of any solution for case 2. But when this question arises case 1 is the usual requirement. In this case my solution is to create an ordinary dot Net property. This will be resolved before any dependency property.

But there may be a problem with the ordinary dot Net property. How do you bind to a reference? A control in the visual tree for e.g.? There is a solution for this, but only available in newer version of XAML. You can write

<MyCustomControl MyParameter="{x:Reference Name=Blah}"/> 

instead of

<MyCustomControl MyNonParameter="{Binding ElementName=Blah}"/> 

And you do not have to create a DP for that. In your custrom control you can just write

class MyCustomControl {     // The parameter my constructor sadly can not have     public MyParameterType MyParameter { get; set; } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!