在 XAML 中命名没有默认构造函数的用户控件 [英] Naming user controls without default constructors in XAML

查看:37
本文介绍了在 XAML 中命名没有默认构造函数的用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a user control without a parameterless constructor; let's call it WithoutDefaultConstructor. I want to insert a WithoutDefaultConstructor called myControl into the XAML code of another control (which is called MainWindow). However, I get this compiler error:

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

The type 'WithoutDefaultConstructor' cannot have a Name attribute. Value types and types without a default constructor can be used as items within a ResourceDictionary.

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

How do I fix this without adding a parameterless constructor to 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>

以下是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;
        }
    }
}

推荐答案

这与 Name 属性无关.您不能使用带有 XAML 参数的构造函数创建对象的实例.有一种方法可以在 XAML 2009 中做到这一点,但是在编译为 BAML 的代码中不可用,例如这个.

It's not about the Name attribute. You just can't create an instance of an object using constructor with parameter from XAML. There is a way to do it in XAML 2009, but it's not available in code compiled to BAML, such as this.

这篇关于在 XAML 中命名没有默认构造函数的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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