WPF TextBox设置在验证期间使用Trigger进行文本

时间:2010-10-04 13:17:24

标签: wpf validation text textbox triggers

我有一个要求,当用户输入错误的输入时,我必须将TextBox的值恢复为旧值。我正在使用MVVM框架,所以我不想写任何代码隐藏。

TextBox的文本和标签是ViewModel变量的数据绑定。所以我的TextBox的Tag字段将始终具有旧值。我想使用标记字段值来恢复我的文本值。

  <Style TargetType="{x:Type TextBox}">
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <DockPanel LastChildFill="True">
                        <TextBlock DockPanel.Dock="Right" 
                    Foreground="Orange"
                    FontSize="12pt">

                </TextBlock>
                        <Border BorderBrush="Red" BorderThickness="1">
                            <AdornedElementPlaceholder />
                        </Border>
                    </DockPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true" >
                <Setter Property="ToolTip" 
                        Value="{Binding Path=Tag,RelativeSource={RelativeSource Self}}">
                </Setter>
                <Setter Property="Text"
                            Value="{Binding Path=Tag,RelativeSource={RelativeSource Self}}">
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>


  <TextBox Width="68" Tag="{Binding SampleText}" Height="23" HorizontalAlignment="Left" Margin="39,37,0,0" VerticalAlignment="Top" >
        <TextBox.Text>
            <Binding Path="SampleText"  NotifyOnValidationError="True" ValidatesOnDataErrors="True" ValidatesOnExceptions="True">
                <Binding.ValidationRules>
                    <val:SampleTextValidator></val:SampleTextValidator>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>        
 </TextBox>


现在发生错误时,TextBox会突出显示为红色。我已写入一个触发器,将值恢复为原始值(存储在Tag字段中的值)。 Tt无法正常工作。但Tooltip部分正在运作。我很困惑。请帮助我在哪里做错!!!如果可能,请使用示例代码纠正我!!!!

1 个答案:

答案 0 :(得分:0)

我的第一个猜测是,当你的文本输入无效时(例如删除所有值),你会导致标签绑定到相同的值,因此,它将反映一个空字符串。

您需要的是一个单独的属性,用于将您的标记绑定到原始值。

private string _oldValue;
public string OldValue
{
    get {...}
    set {... NotifyPropertyChanged()...}
}

private string _sampleText;
public string SampleText
{
    get { return _sampleText; }
    set {
            OldValue = _sampleText;
            _sampleText = value;
            NotifyPropertyChanged(...);
        }
}

<TextBox Width="68" Tag="{Binding OldValue}" ... >

不要忘记实施INotifyPropertyChanged。