我有一个自定义组件,它基本上是一个带有附加按钮的文本框。该按钮应该对文本框执行操作;例如,单击按钮可以用一些随机字符串填充文本框。
文本字段绑定(bind)到 ViewModel 中的属性。它基本上看起来像这样:
设置组件通用命令的最佳方法是什么?
到目前为止,我所做的是在我的 ViewModel 中有一个需要参数的通用 RelayCommand
。每个按钮都将其命令设置为该单个命令,我使用 CommandParameter
属性添加一些关于我实际谈论的文本字段组件的信息。然后 ViewModel 使用该信息找出正确的属性并更改其值(通过绑定(bind)更新文本框)。
虽然这工作正常,但我不喜欢我必须手动插入有关相关文本框或上下文的信息。理想情况下,我希望在已经知道它正在谈论哪个文本框或绑定(bind)属性的上下文范围内执行命令。有什么方法可以做到这一点吗?
我遇到的另一个问题是我想将按钮操作绑定(bind)到一个键命令。因此,当我聚焦文本框并按下快捷键时,我希望它的行为就像我单击了正确按钮一样,即执行命令并传递正确的上下文信息。我的替代方案是将其放入代码隐藏中,基本上从当前焦点中提取命令参数,但我更喜欢更简洁的解决方案。
有什么好的方法可以使它与 MVVM 一起工作吗?
最佳答案
按照这些思路怎么样:
public class TextBoxAndCommandPresenter : INotifyPropertyChanged
{
private readonly Action<TextBoxAndCommandPresenter> _action;
public TextBoxAndCommandPresenter(string description,
Action<TextBoxAndCommandPresenter> action)
{
Description = description;
_action = action;
}
public string Description { get; private set; }
public string Value { get; set; }
public ICommand Command
{
get { return new DelegateCommand(() => _action(this)); }
}
}
这样使用:
var presenter = new TextBoxAndCommandPresenter("Field 1",
p => p.Value = "hello world");
使用 XAML:
<UserControl ...>
<UserControl.Resources>
<DataTemplate DataType="{x:Type TextBoxAndCommandPresenter}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Description}"/>
<TextBox Text="{Binding Value}"/>
<Button Command="{Binding Command}">Click</Button>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<ContentPresenter Content="{Binding}"/>
</UserControl>
关于c# - MVVM 的上下文相关命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263080/