在我的 WPF 应用程序中,我有一个 TextBox 和一个 Button。该按钮有一个命令绑定到一个将对文本执行某些操作的命令。
<TextBox x:Name="_textBox"></TextBox>
<Button Command="{Binding SomeCommand}"
CommandParameter="{Binding ElementName=_text, Path=Text}"
Content="Trigger SomeCommand" />
现在,我希望单击按钮的操作也清除 TextBox。这样做的最佳方法是什么?我看到两个选项:
我也可以在 Button 上添加一个 Click 事件 - 使文本清晰。这对我来说听起来不是一个好主意,因为我会将动作分成两个地方,依赖于它们执行的顺序是否正确。
我现在使用的选项是传递整个 TextBox 而不是 TextBox.Text 属性。这样做该命令可以首先获取文本,使用它,然后清除 TextBox。我的绑定是相同的,但没有“路径”:
<TextBox x:Name="_textBox"></TextBox>
<Button Command="{Binding SomeCommand}"
CommandParameter="{Binding ElementName=_text}"
Content="Trigger SomeCommand" />
我的命令的基本部分:
public class SomeCommand : ICommand
{
....
public void Execute(object parameter)
var textBox = parameter as TextBox;
if (inputTextBox == null) return;
DoSomething(textBox.Text);
textBox.Clear();
}
}
我的问题是该命令现在依赖于 UI 组件,并且 UI 依赖于命令来实际对其进行一些修改。我对此并不完全满意。有没有更好的办法?