0

我有一个与这样的命令相关联的文本框:

<TextBox Text="{Binding Path=TextContent, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>
            <KeyBinding Command="{Binding Path=MyCommand}" Key="Enter" />
        </TextBox.InputBindings>
</TextBox>

该属性TextContent是在 ViewModel 中定义的字符串。该命令MyCommand也在 ViewModel 中定义。ViewModel 不知道 View。

只要 TextBox 具有焦点并按下回车键,就会调用该命令。不幸的是,如果CanExecute返回 false,则用户无法(视觉上)看到该命令未执行,因为 TextBox 中没有视觉上的变化。

我正在寻找有关如何向用户显示该命令在他按下回车后无法执行的建议。

我的想法(以及我对它们的怀疑):

  • CanExecute返回时禁用 TextBox false:这不是选项,因为CanExecute每次键入/更改字母时,返回值都会发生变化(TextBox 中的文本会影响 的结果CanExecute)。当它第一次被禁用时,用户不能再输入它,所以它将永远保持禁用状态。

  • 显示一个消息框,说明命令未执行:记住,ViewModel 不知道 View。甚至可以从 ViewModel 打开一个消息框吗?此外,我应该在哪里调用打开消息框?不在里面CanExecute,因为我只想在按 enter 后获取消息框,而不是每次都CanExecute返回false。也许 makeCanExecute总是返回true并在内部进行检查Execute:如果检查正常,则执行命令,否则,向用户显示一些消息。但是,CanExecute完全错过了拥有的意义……

我想保留 MVVM,但是一些用于将内容重定向到 ViewModel 的代码隐藏对我来说似乎没问题。

4

2 回答 2

1

我建议以下解决方案。

这是一个关于如何通知我目前正在处理的用户的示例。

我希望用户输入 int、double 或 string 类型的数据限制。它想检查用户是否输入了正确的类型。我使用属性ValidateLimits检查字符串MyLimits,在您的情况下是TextContent

每次用户在 TextBox 中输入任何内容时,ValidateLimits 都会检查该字符串。如果它不是文本框中的有效字符串,则返回 false,否则返回 true。如果为 false,则通过在 TextBox 上设置一些属性来使用 DataTrigger 突出显示它,在我的例子中是一些边框和前景色,也是一个工具提示。

同样在您的情况下,您想在CanExecute方法中调用您的 Validate方法。

如果您已经具有检查命令是否正常的功能,则只需将其添加到 DataTrigger 绑定。

<TextBox Text="{Binding MyLimit1, UpdateSourceTrigger=PropertyChanged}" Margin="-6,0,-6,0">
  <TextBox.Style>
    <Style TargetType="TextBox">
     <!-- Properties that needs to be changed with the data trigger cannot be set outside the style. Default values needs to be set inside the style -->
     <Setter Property="ToolTip" Value="{Binding FriendlyCompareRule}"/>
       <Style.Triggers>
         <DataTrigger Binding="{Binding ValidateLimits}" Value="false">
           <Setter Property="Foreground" Value="Red"/>
           <Setter Property="BorderBrush" Value="Red"/>
           <Setter Property="BorderThickness" Value="2"/>
           <Setter Property="ToolTip" Value="Cannot parse value to correct data type"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBox.Style>

public bool ValidateLimits
{
  get
  {
    // Check if MyLimit1 is correct data type
    return true/false;
  }
}
于 2016-10-05T08:55:20.520 回答
0

bool IsCommandExecuted在您的Command班级中使用属性。相应地设置此属性。

使用 aToolTip并将其IsOpen属性绑定到IsCommandExecuted如下属性:

<TextBox ...>
    <TextBox.ToolTip>
        <ToolTip IsOpen="{Binding MyCommand.IsCommandExecuted}">...</ToolTip>
    </TextBox.ToolTip>
</TextBox>

这解释了这个概念,并相应地修改它。

于 2016-10-05T09:11:37.213 回答