如何在wpf控件构造函数中传递参数?

c8ib6hqw  于 2022-11-26  发布在  其他
关注(0)|答案(2)|浏览(356)

我写了我的控件,并试图传递参数的额外初始化,但有错误=((tHE类型调整控件不能有一个名称属性).如何正确传递数据?这是我的代码在C#:

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

错误:错误15类型“AjustControl”不能具有Name属性。值类型和没有默认构造函数的类型可以用作ResourceDictionary中的项。行470位置26。D:\Prj\aaa\MainWindow.xaml 470 26 Studio

1wnzp6jl

1wnzp6jl1#

因此,正如错误所述,在xaml中不能有没有无参数构造函数的控件。如果你想从代码中示例化它,你仍然可以添加一个,但是xaml不会调用那个构造函数。

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

public AjustControl()
{
    InitializeComponent();
}

不过,如果您要求将自订属性加入至控件,则可以加入DependancyProperty

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

在此之后,您可以使用控件,如

<custom:AjustControl Name="something" />
0h4hbjxa

0h4hbjxa2#

您的问题并不清楚为何需要将参数传递至自订控件的建构函式。
1.这可能是因为您需要自订控件先使用违规的参数,然后再透过相依性属性机制(最明显的是会直接或间接使用违规建构函式参数的系结属性),将任何系结值从自订控件传递至父代。
1.这可能是因为无论出于什么原因,通过参数化构造函数进行初始化都是您唯一的选择。
我不知道情况2的任何解决方案。但当这个问题出现时,情况1是通常的要求。在这个情况下,我的解决方案是创建一个普通的. Net属性。这将在任何依赖属性之前解决。
但是普通的. Net属性可能会有问题。如何绑定到引用?例如,可视化树中的控件?有一个解决方案,但仅在较新版本的XAML中可用。您可以编写

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

代替

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

您不必为此创建DP。在custrom控件中,您只需编写

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

相关问题