如何在wpf控件构造函数中传递参数? [英] how to pass parameter in wpf control constructor?

查看:73
本文介绍了如何在wpf控件构造函数中传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了我的控件并尝试传递参数以进行额外的初始化,但出现错误 =((tHE TYPE Ajustcontrol 不能有名称属性).如何正确传递数据?这是我在 C# 中的代码:

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);

        }

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

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

推荐答案

所以,正如错误所说.在 xaml 中,如果没有无参数构造函数,您将无法拥有控件.如果您想从代码中实例化它,您仍然可以添加一个,但 xaml 不会调用该构造函数.

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

但是,如果您要求向控件添加自定义属性,则可以添加 DependancyProperty.

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" />

这篇关于如何在wpf控件构造函数中传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆