6

パラメータなしのコンストラクタなしでユーザーコントロールがあります。それを呼びましょうWithoutDefaultConstructor。別のコントロール(と呼ばれる)のXAMLコードにWithoutDefaultConstructor呼び出されたものを挿入したいと思います。ただし、次のコンパイラエラーが発生します。myControlMainWindow

タイプ'WithoutDefaultConstructor'はName属性を持つことができません。値の型とデフォルトのコンストラクターのない型は、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

2 に答える 2

7

それはName属性についてではありません。XAMLのパラメーターを使用してコンストラクターを使用してオブジェクトのインスタンスを作成することはできません。XAML 2009でそれを行う方法はありますが、このようなBAMLにコンパイルされたコードでは使用できません。

于 2011-05-27T19:56:04.007 に答える
4

ただそれをしないでください。代わりに、intユーザーコントロールのプロパティを公開します。明示的に設定されていることを本当に確認したい場合は、を公開し、設定されているint?場合はスローしnullます。

于 2011-05-27T19:47:35.007 に答える