【问题标题】:WPF TextBox setting Text using Trigger during validationWPF TextBox 在验证期间使用触发器设置文本
【发布时间】:2010-10-04 13:17:23
【问题描述】:

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

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

  <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 不工作。但工具提示部分正在工作。我完全糊涂了。请帮助我在哪里做错了!!!!如果可能的话,用示例代码纠正我!!!!

【问题讨论】:

    标签: wpf validation text textbox triggers


    【解决方案1】:

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

    你需要一个单独的属性来为你的原始值绑定你的标签。

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 2011-05-20
      相关资源
      最近更新 更多