【发布时间】:2012-05-02 12:32:51
【问题描述】:
我创建了一些具有可绑定“ClearCommand”ICommand 依赖属性的自定义控件(不是用户控件)。这个属性将完全按照它的意思做:它将清除控件中的所有值(文本框等)。我还将(一些)相同的属性绑定到我在下面描述的 VM。
现在我被困在尝试在以下 MVVM 场景中触发这些控件中的 ClearCommand:
我在视图中添加了一些这样的控件。该视图还包括一个“保存”按钮,该按钮绑定到我的 ViewModel 的 SaveCommand DelegateCommand 属性。
我需要做的是,在成功保存后,VM 应该在 View 中找到的那些控件上触发 ClearCommand。
更新
我在下面添加了代码示例。我有一些类似于 ExampleCustomControl 的控件。另外,请注意,如果它完全关闭,我愿意重组其中的一些。
示例控件 sn-p:
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;
}
}
示例视图 sn-p:
<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
}
}
【问题讨论】:
-
通常,我的命令在我的 ViewModel 上。在 ViewModel 中,您可以调用
MyCommand.Execute();。如果这不是您的项目的结构,请发布一些代码以澄清。 -
作为一种快速解决方法,您可以在注册 SelectedIOtemProperty 时在 PropertyMetadata 中设置 PropertyChangedCallback,并在回调中清除您想要的所有内容。但是,我建议您考虑重组您的设置并将清除与所有绑定属性一起放入 VM。
-
我的问题是将 ExampleCustomControl 的所有属性绑定到视图模型的问题是重用。我希望搜索逻辑/等位于自定义控件中,并且我希望能够在几个不同的视图中重用相同的控件。
标签: wpf mvvm user-controls