WPF TextBox 在验证上设置红色边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37152078/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:48:11  来源:igfitidea点击:

WPF TextBox setting red border on Validation

c#wpfvalidation

提问by Piotr Lazarczyk

I'm trying to make textbox's border red when it's empty. Here's my xaml:

我试图在文本框为空时将其边框设为红色。这是我的 xaml:

     <TextBox  Style="{StaticResource TextBoxEmptyError}" Name="tbFilename" Grid.Column="1" >
         <Binding Path="Text" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <local:EmptyRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox>

style i'm trying to set:

我正在尝试设置的样式:

        <Style x:Key="TextBoxEmptyError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="True">
                    <Setter Property="BorderThickness" Value="2" />
                    <Setter Property="BorderBrush" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>

EmptyRule:

空规则:

public class EmptyRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (string.IsNullOrEmpty(value as string))
                return new ValidationResult(false, null);
            else
                return new ValidationResult(true, null);

        }
    }

In debugger it looks like Validation method isn't used at all. What am I doing wrong?

在调试器中,看起来根本没有使用 Validation 方法。我究竟做错了什么?

采纳答案by StepUp

I cannot see where you set DataContextbetween XAML and viewModel.

我看不到您DataContext在 XAML 和 viewModel 之间设置的位置。

DataContextis a way to know where XAML(View, your Window) can get data from.

DataContext是一种了解 XAML(View, your Window) 可以从何处获取数据的方法。

For example, you have model class:

例如,您有模型类:

internal class SomeUser
{        
    private string _name;
    private string _address;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
        }
    }

    public string Address
    {
        get { return _address; }
        set { _address = value; }
    }
}

Then you should set DataContextto your Window. For example, in code-behind:

然后你应该设置DataContext为你的Window. 例如,在代码隐藏中:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new SomeUser();       
    }
}

then XAML should looks like this:

那么 XAML 应该是这样的:

<Grid>
  <Grid.Resources> 
     <Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBox}">
                        <Border x:Name="bg" BorderBrush="#FF825E5E" BorderThickness="1">
                            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Border>
                        <ControlTemplate.Triggers>

                            <Trigger Property="Validation.HasError" Value="True">
                                <Trigger.Setters>
                                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>                                        
                                    <Setter Property="BorderThickness" TargetName="bg" Value="2"/>
                                    <Setter Property="BorderBrush" TargetName="bg" Value="Red"/>
                                </Trigger.Setters>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
</Grid>

<TextBox Style="{StaticResource CustomTextBoxTextStyle}" Height="23" Name="textBox1" Margin="25">
            <Validation.ErrorTemplate>
                <ControlTemplate>
                    <DockPanel>
                        <TextBlock Foreground="Red" DockPanel.Dock="Right">!</TextBlock>
                        <AdornedElementPlaceholder x:Name="ErrorAdorner"
    ></AdornedElementPlaceholder>
                    </DockPanel>
                </ControlTemplate>
            </Validation.ErrorTemplate>

            <TextBox.Text>
                <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:NameValidator></local:NameValidator>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
</TextBox>

回答by Jan Paolo Go

your Bindingto Textshould be like this...

BindingText应该是这样的...

<Binding Path="Text" UpdateSourceTrigger="LostFocus" Mode="OneWayToSource" NotifyOnValidationError="True" RelativeSource="{RelativeSource Self}">