相关疑难解决方法(0)

在XAML中命名没有默认构造函数的用户控件

我有一个没有无参数构造函数的用户控件; 我们称之为WithoutDefaultConstructor.我想将一个WithoutDefaultConstructor被调用的myControl插入另一个控件(被调用MainWindow)的XAML代码中.但是,我收到此编译器错误:

"WithoutDefaultConstructor"类型不能具有Name属性.没有默认构造函数的值类型和类型可以用作ResourceDictionary中的项.

如何在不添加无参数构造函数的情况下解决此问题WithoutDefaultConstructor

以下是内容MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" 
 Height="350" Width="525">
    <WpfApplication1:WithoutDefaultConstructor Name="myControl">
    </WpfApplication1:WithoutDefaultConstructor>
</Window>
Run Code Online (Sandbox Code Playgroud)

以下是内容WithoutDefaultConstructor.xaml.cs:

using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class WithoutDefaultConstructor : UserControl
    {
        private int I_really_need_to_initialize_this_int;

        public WithoutDefaultConstructor(int i)
        {
            InitializeComponent();
            I_really_need_to_initialize_this_int = i;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

wpf xaml default-constructor

6
推荐指数
1
解决办法
6725
查看次数

标签 统计

default-constructor ×1

wpf ×1

xaml ×1