开发者

TextBox with Data Binding should display helper text when empty

I am working on an application in C# using the .NET Framework 3.5. I have a TextBox on one of my forms that is bound to the "ID" property of the DataContext of the form, like so:

<TextBox x:Name="txtID" 
    Grid.Row="0" Grid.Column="1" 
    Margin="2" MinWidth="200" VerticalAlignment="Top"
    Style="{StaticResource validationToolTip}"
    >
    <TextBox.Text>
        <Binding Path="ID" UpdateSourceTrigger="PropertyChanged"    
            ValidatesOnDataErrors="true">
            <Binding.ValidationRules>
                <ui:RequiredFieldValidationRule />
            开发者_高级运维</Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

I would like the TextBox to display some helper text ("[Leave blank to auto-generate.]") when the ID property is empty and the TextBox does not have input focus. I am considering styling this text differently (italicize) to distinguish it from a user-typed ID. Since the TextBox.Text property is bound to the ID property, however, I want to make sure that my solution doesn't cause the ID property to be set to the value of my helper string. How should I go about implementing this behavior?


The simplest approach would be to have a label over the text box to contain the text, or use a tooltip for the text Another approach would be to have a class sit between the control and the data class that you are currently bound to. This class could then pass the required '[Leave blank to auto-generate.]' text if the text in the data class is empty, or pass through the value if it is not. For all the other fields the value would just be a pass through


Here's a straightforward approach that can pretty trivially be turned into a control template or a user control:

<Grid>
  <TextBox 
     Foreground="LightGray" 
     Focusable="False"
     Text="This is the help text."/>
  <TextBox 
     Focusable="True"
     Text="The help text only displays if this is empty.">
    <TextBox.Style>
      <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Triggers>
          <DataTrigger 
             Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}"                   
             Value="">
            <Setter Property="Background" Value="Transparent"/> 
          </DataTrigger>
        </Style.Triggers>             
      </Style>
    </TextBox.Style>
  </TextBox>
</Grid>

Note that the internal style set here is based on the default style for the TextBox, so this should continue to display properly if you globally restyle the TextBox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜