私は明らかにこれをどこかで理解していません。
私は UserControl を作成しました。その基本要素は次のとおりです。
private readonly DependencyProperty SaveCommandProperty =
DependencyProperty.Register("SaveCommand", typeof(ICommand),
typeof(ctlToolbarEdit));
private readonly DependencyProperty IsSaveEnabledProperty =
DependencyProperty.Register("IsSaveEnabled", typeof(bool),
typeof(ctlToolbarEdit), new PropertyMetadata(
new PropertyChangedCallback(OnIsSaveEnabledChanged)));
public ctlToolbarEdit()
{
InitializeComponent();
}
public bool IsSaveEnabled
{
get { return (bool)GetValue(IsSaveEnabledProperty); }
set { SetValue(IsSaveEnabledProperty, value); }
}
public static void OnIsSaveEnabledChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
((ctlToolbarEdit)d).cmdSave.IsEnabled = (bool)e.NewValue;
}
#region Command Handlers
public ICommand SaveCommand
{
get { return (ICommand)GetValue(SaveCommandProperty); }
set { SetValue(SaveCommandProperty, value); }
}
private void cmdSave_Click(object sender, RoutedEventArgs e)
{
if (SaveCommand != null)
SaveCommand.Execute(null);
}
#endregion
優秀な。ボタンのクリック イベントを処理し、基本的にコマンドを起動しています。
コントロールをホストしているフォーム(当分の間 Form1 を呼び出します...ただし、これは実際には UserControl であることに注意してください。MVVM では一般的な方法だと思います)には、次の行があります。
<ctl:ctlToolbarEdit HorizontalAlignment="Right" Grid.Row="1"
SaveCommand="{Binding Save}" IsSaveEnabled="{Binding IsValid}" />
これはうまくいきます。ViewModelに「Save」というICommandがあり、ViewModelはIsValidプロパティを正しく表示しています。
これまでのところ、とても良いです。
ここで、新しいユーザーコントロールを Form2 でも使用したいと考えています (これはユーザーコントロールでもあります - MVVM では一般的な方法だと思います)。たまたま、Form1 と Form2 が同時に画面に表示されています。
コンパイルはできますが、実行時例外が発生します:
'SaveCommand' プロパティは 'ctlToolbarEdit' によって既に登録されています。"
...「コマンド」がまったく得られないと信じるようになりました。
ユーザーコントロールを複数の場所で使用できないのはなぜですか?
できない場合、これを行う別の方法は何ですか?
非常にイライラします!
助けてくれてありがとう。