【问题标题】:Modifying UI from commands - using command binding in WPF从命令修改 UI - 在 WPF 中使用命令绑定
【发布时间】:2010-02-08 10:20:41
【问题描述】:

在我的 WPF 应用程序中,我有一个文本框和一个按钮。该按钮有一个命令绑定到一个将对文本执行某些操作的命令。

<TextBox x:Name="_textBox"></TextBox>
<Button Command="{Binding SomeCommand}" 
        CommandParameter="{Binding ElementName=_text, Path=Text}"
        Content="Trigger SomeCommand" />

现在,我希望单击按钮的动作也清除文本框。这样做的最佳方法是什么?我看到两个选项:

我也可以在 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 依赖于命令来实际对其进行一些修改。我对此并不完全满意。有没有更好的办法?

【问题讨论】:

    标签: c# wpf commandbinding


    【解决方案1】:

    请考虑将文本框文本绑定到 Command 实现主体中可用的属性。进行此绑定后,您可以轻松地从 ViewModel 中清除它。

    示例 (XAML):

    <TextBox x:Name="_textBox" Text={Binding Path=XYZ}></TextBox>
    <Button Command="{Binding SomeCommand}"
            Content="Trigger SomeCommand" />
    

    示例(C#):

        public class SomeCommand : ICommand
        {
            ....
    
             public void Execute(object parameter)
             {
                //...actions...
                MyViewModelinstance.XYZ = String.Empty;
            }
        }
    

    如果可行,请大声告诉我。

    编辑:您使用的是 MVVM 设计模式,所以应该很明显,但我会提醒一下以防万一:更改 XYZ 后,您必须通知 UI,此属性已更改.例如,您可以通过 VM 实现 INotifyPropertyChanged 接口来做到这一点。

    【讨论】:

    • 我正在使用 MVVM 模式,听起来你是对的。我会将文本字段绑定到同一 ViewModel 的某个属性,该 ViewModel 包含需要清除它的命令。我相信这听起来很合理。明天会仔细看看。谢谢!
    • 拜托,我相信它会帮助你。
    • 你说得对。没有完全按照建议的那样做,但本质上我将值存储在ViewModel中,并使命令使用存储在ViewModel中的值,然后将其清除。谢谢!
    • 太棒了! :) 请将此答案标记为已接受,以便其他人遇到您的问题。
    猜你喜欢
    • 2016-05-07
    • 2013-04-25
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多