可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
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.
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; }