このような単純な動作をする再利用可能なコントロール用に、個別のViewModelを作成する必要はありません。いくつかのDependencyPropertiesとイベントハンドラーを単純なUserControlに追加するだけで、ロジックを再利用して、インスタンスごとに実際に異なるプロパティのみを設定できます。UserControl XAMLの場合は、TextBoxをDependencyPropertyに接続し、ButtonをClickハンドラーに接続する必要があります。
<DockPanel>
<Button Content="Reset" Click="Button_Click"/>
<TextBox Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=Text}"/>
</DockPanel>
UserControlのコードは、外部でバインドできるプロパティと、テキストをリセットするためのハンドラーを定義する必要があります。
public partial class ResetTextBox : UserControl
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(ResetTextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty ResetTextProperty = DependencyProperty.Register(
"ResetText",
typeof(string),
typeof(ResetTextBox),
new UIPropertyMetadata(String.Empty));
public string ResetText
{
get { return (string)GetValue(ResetTextProperty); }
set { SetValue(ResetTextProperty, value); }
}
public ResetTextBox()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Text = ResetText;
}
}
次に、コントロールを使用するには、ViewModel文字列プロパティにバインドし、ここでハードコーディングするか、他のVMプロパティにバインドできるリセット時に適用するデフォルトのテキストを設定する必要があります。
<StackPanel>
<local:ResetTextBox ResetText="One" Text="{Binding Name1}"/>
<local:ResetTextBox ResetText="Two" Text="{Binding Name2}"/>
<local:ResetTextBox ResetText="Three" Text="{Binding Name3}"/>
</StackPanel>