バインド可能な「ClearCommand」ICommand 依存関係プロパティを使用して、いくつかのカスタム コントロール (UserControl ではない) を作成しました。このプロパティは、まさにそのとおりに動作します。コントロール (テキスト ボックスなど) からすべての値をクリアします。また、これらの同じプロパティの (一部) を、以下で説明する VM にバインドします。
次のMVVMシナリオで、これらのコントロールでClearCommandをトリガーしようとして立ち往生しています。
そのようなコントロールをビューにいくつか追加しました。SaveCommand
DelegateCommand
ビューには、ViewModel のプロパティにバインドする [保存] ボタンも含まれています。
私がする必要があるのは、保存が成功すると、VM がClearCommand
ビューで見つかったコントロールをトリガーすることです。
アップデート
以下にコード例を追加しました。ExampleCustomControl に似たコントロールがいくつかあります。また、完全にオフになっている場合は、これの一部を再構築することにオープンです。
制御スニペットの例:
public class ExampleCustomControl : Control {
public string SearchTextBox { get; set; }
public IEnumerable<CustomObject> ResultList { get; set; }
public ExampleCustomControl() {
ClearCommand = new DelegateCommand(Clear);
}
/// <summary>
/// Dependency Property for Datagrid ItemSource.
/// </summary>
public static DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem",
typeof(CustomObject), typeof(ExampleCustomControl), new PropertyMetadata(default(CustomObject)));
public CustomObject SelectedItem {
get { return (CustomObject)GetValue(SelectedCustomObjectProperty); }
set { SetValue(SelectedCustomObjectProperty, value); }
}
public static DependencyProperty ClearCommandProperty = DependencyProperty.Register("ClearCommand", typeof(ICommand),
typeof(ExampleCustomControl), new PropertyMetadata(default(ICommand)));
/// <summary>
/// Dependency Property for resetting the control
/// </summary>
[Description("The command that clears the control"), Category("Common Properties")]
public ICommand ClearCommand {
get { return (ICommand)GetValue(ClearCommandProperty); }
set { SetValue(ClearCommandProperty, value); }
}
public void Clear(object o) {
SearchTextBox = string.Empty;
SelectedItem = null;
ResultList = null;
}
}
ビューのスニペットの例:
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<control:ExampleCustomControl Grid.Row="0"
SelectedItem="{Binding Selection, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Row="1" x:Name="ResetButton" Command="{Binding SaveCommand}">
Save
</Button>
</Grid>
ビューモデルの例:
public class TestViewModel : WorkspaceTask {
public TestViewModel() {
View = new TestView { Model = this };
SaveCommand = new DelegateCommand(Save);
}
private CustomObject _selection;
public CustomObject Selection {
get { return _selection; }
set {
_selection = value;
OnPropertyChanged("Selection");
}
}
public DelegateCommand SaveCommand { get; private set; }
private void Save(object o) {
// perform save
// clear controls
}
}