我有一個沒有無參數構造函數的用戶控件;我們稱之爲WithoutDefaultConstructor
。我想插入名爲myControl
的WithoutDefaultConstructor
到另一個控件(稱爲MainWindow
)的XAML代碼中。不過,我得到這個編譯器錯誤:命名XAML中沒有默認構造函數的用戶控件
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
?
這裏是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;
}
}
}