来自其他对象的 wpf 命令参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15273233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wpf command parameter from other object
提问by DRapp
I'm wondering how to mark up the XAML for the following. I have a view model with an object based on ICommand.
我想知道如何为以下内容标记 XAML。我有一个基于ICommand.
I have a form with a textbox and a button. The button is hooked to the ICommandobject via Command="{Binding MyButtonInViewModel}".
我有一个带有文本框和按钮的表单。该按钮ICommand通过连接到对象Command="{Binding MyButtonInViewModel}"。
What I want to do is set the button's CommandParameterequal to whatever is in the text of the textbox such as to invoke a "Search", but obviously don't know how to hook across controls in the view.
我想要做的是将按钮设置为CommandParameter等于文本框文本中的任何内容,例如调用“搜索”,但显然不知道如何在视图中跨控件挂钩。
回答by Jehof
The following XAML should work to pass the Text from the TextBox as Parameter to your command.
以下 XAML 应该可以将 TextBox 中的文本作为参数传递给您的命令。
<TextBlock x:Name="searchBox" />
<Button Command="{Binding MyButtonInViewModel}"
CommandParameter="{Binding Text, ElementName=searchBox}"/>
回答by Tomtom
You can do this by setting the ElementNamein the binding.
Here's an example:
您可以通过ElementName在绑定中设置 来做到这一点。下面是一个例子:
<TextBox x:Name="textBox"/>
<Button Content="Button"
Command="{Binding ButtonCommand}"
CommandParameter="{Binding ElementName=textBox, Path=Text}"/>
回答by BrianHoyt
If you bind the textbox itself to the button's command parameter, and not just the text property of the text box, you can manipulate the textbox in your view model to, for instance, clear the text property.
如果将文本框本身绑定到按钮的命令参数,而不仅仅是文本框的 text 属性,则可以在视图模型中操作文本框,例如清除 text 属性。
<TextBox x:Name="searchBox" />
<Button Command="{Binding MyButtonInViewModel}"
CommandParameter="{Binding ElementName=searchBox}" />
View Model Code
查看型号代码
private void SearchStuff(TextBox searchBox)
{
//do stuff with searchBox.Text
searchBox.Text = "";
}
Maybe not great for this example, where you probably want the search text to stay displayed along with the results of the search. Better for a logging or messaging app where you want the text to be 'consumed' when the button is clicked.
对于这个例子来说可能不太好,您可能希望搜索文本与搜索结果一起显示。更适合用于在单击按钮时“使用”文本的日志记录或消息传递应用程序。

