2011-05-27 51 views
6

我有一個沒有無參數構造函數的用戶控件;我們稱之爲WithoutDefaultConstructor。我想插入名爲myControlWithoutDefaultConstructor到另一個控件(稱爲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; 
     } 
    } 
} 

回答

4

只是不去做。相反,請在用戶控件上公開int屬性。如果你真的想要確保它明確設置,請公開int?並拋出,如果它是null

相關問題