【问题标题】:Make TextBox border red when value is empty by using databinding in MVVM Light通过在 MVVM Light 中使用数据绑定,当值为空时使 TextBox 边框变为红色
【发布时间】:2015-10-15 15:06:47
【问题描述】:

当值为空时,我可以使 TextBox 变为红色,但只有在我单击按钮之后。但是如何在不点击按钮的情况下使其为空时变为红色?

我正在使用 MVVM Light,它与“TwoWay”有关吗?还是 RaisePropertyChanged 或 OnpropertyChanged?

这是我的 xaml 中的一个文本框:

 <TextBox Text="{Binding SelectedPerson.FirstName, Mode=TwoWay}"
                 Width="200"
                 HorizontalAlignment="Left"
                 Background="Grey"
                 Foreground="White"
                 BorderThickness="1"
                 BorderBrush="{Binding Color, Mode=TwoWay}" />

这是我的 ViewModel 上的代码:

 private SolidColorBrush _Color;
    public SolidColorBrush Color
    {
        get
        {
            return _Color;
        }
        set
        {
            _Color = value;
            RaisePropertyChanged("Color");
        }
    }

那么这是按钮命令:

 public RelayCommand UpdatePerson
    {
        get
        {
            return new RelayCommand(async () =>
            {
                Color = new SolidColorBrush(Colors.Red);
                //....      
            });
        }
    }

所以我想要的是,当 FirstName TextBox 为空时,边框变为红色,而无需单击按钮。

 private Person _SelectedPerson;
    public Person SelectedPerson
    {
        get
        {
            return _SelectedPerson;
        }
        set
        {
            _SelectedPerson = value;
            if (value.FirstName == "")
            {
                Color = new SolidColorBrush(Colors.Red);
            }
            RaisePropertyChanged("SelectedPerson");
        }
    }

【问题讨论】:

  • 您可以在SelectedPerson.FirstName 属性设置器处更改Color
  • @Alexander 我试过了,但没用。
  • 它应该可以工作。你能显示你的代码吗?实际上这不是实现数据验证的好方法。 WPF 为此提供了几个功能,例如ValidationRuleExceptionValidationRule
  • @Alexander 在最后添加了这段代码。这不是 wpf,而是一个 windows 通用应用程序。
  • 正如@Robert 所说,您需要将Color 更改为SelectedPerson.FirstName setter(而不是SelectedPerson

标签: c# xaml data-binding mvvm-light


【解决方案1】:

如果您只是想将所有不包含任何值的字段变为红色,您可以使用它

<Style.Triggers>
 <Trigger Property="Text" Value="">
 <Setter Property="BorderBrush" Value="Red"></Setter>
 </Trigger>
 </Style.Triggers>

【讨论】:

    【解决方案2】:

    SelectedPerson.FirstName 设置器更改 Color 并确保在 Text 属性的绑定中将 UpdateSourceTrigger 设置为 PropertyChanged


    编辑 1

    针对您的评论,我建议您在 ViewModel 中实现 FirstName 属性,如下所示:

    public String FirstName
    {
        get { return SelectedPerson.FirstName; }
        set
        {
            SelectedPerson.FirstName = value;
            // Update 'Color' here
        }
    }
    

    然后在视图中,Text 属性的绑定将如下所示:

    {Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
    

    而不是

    {Binding SelectedPerson.FirstName, Mode=TwoWay}
    

    【讨论】:

    • 我没有 SelectedPerson.Firstname 设置器,因为这是 SelectedPerson 的一部分。
    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多