繁体   English   中英

WPF TextBox设置在验证期间使用触发器的文本

[英]WPF TextBox setting Text using Trigger during validation

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

TextBox的Text和Tag是从ViewModel变量进行数据绑定的。 因此,我的TextBox标记字段将始终具有旧值。 我想使用“标记”字段值还原我的“文本”值。

  <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>


现在,当发生错误时,文本框将突出显示为红色。我编写了一个触发器将值恢复为原始值(存储在“标记”字段中的值)。 Tt无法正常工作。 但是工具提示部分正在工作。 我很困惑。 请帮助我在哪里做错了! 如果可能,请使用示例代码纠正我!!!!

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

您需要一个单独的属性来将您的原始值绑定到标签。

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM