Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming user controls without default constructors in 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:

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;
        }
    }
}
like image 477
user181813 Avatar asked May 27 '11 19:05

user181813


2 Answers

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.

like image 113
svick Avatar answered Oct 15 '22 22:10

svick


Just don't do it. Instead, expose an int property on your user control. If you really want to make sure it's explicitly set, expose an int? and throw if it's null.

like image 4
Kent Boogaart Avatar answered Oct 15 '22 22:10

Kent Boogaart