WPF 项目 + Prism 7 +(纯 MVVM 模式)
TextBox
很简单,当按下某个按钮时,我需要清除哪些(不违反 MVVM 模式)
<Button Command="{Binding ClearCommand}"/>
<TextBox Text="{Binding File}">
<i:Interaction.Behaviors>
<local:ClearTextBehavior ClearTextCommand="{Binding ClearCommand, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
</TextBox>
视图模型
public class ViewModel {
public ICommand ClearCommand { get; set; }
}
行为
public class ClearTextBehavior : Behavior<TextBox>
{
public ICommand ClearTextCommand
{
get { return (ICommand)GetValue(ClearTextCommandProperty); }
set
{
SetValue(ClearTextCommandProperty, value);
RaisePropertyChanged();
}
}
public static readonly DependencyProperty ClearTextCommandProperty =
DependencyProperty.Register(nameof(ClearTextCommand), typeof(ICommand), typeof(ClearTextBehavior));
public ClearTextBehavior()
{
ClearTextCommand = new DelegateCommand(ClearTextCommandExecuted);
}
private void ClearTextCommandExecuted()
{
this.AssociatedObject.Clear();
}
}
问题是 ViewModel 中的命令始终为空(它没有绑定到 Behavior 中的命令),尽管我确保它是在行为类中初始化的。
注意:请不要建议将 File 属性设置为空字符串,因为这只是一个示例,在我的实际情况中,我需要选择所有文本,所以我真的需要访问AssociatedObject
行为