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:
The type 'WithoutDefaultConstructor' cannot have a Name attribute. Value types and types without a default constructor can be used as items within a ResourceDictionary.
How do I fix this without adding a parameterless constructor to WithoutDefaultConstructor
?
Here are the contents of 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>
Here are the contents of 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;
}
}
}
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.