如何在WPF中为搜索框实现默认文本?

Yos*_*age 7 wpf search textbox

我想为WPF搜索TextBox 实现与" 更改搜索框中的默认文本 "完全相同的内容.当文本被输入时,该框应该显示一些灰色的"搜索..."文本,然后它应该在输入文本时正常运行.链接的文章显示了如何在javascript中执行此操作.如何在WPF中开始这条路?到目前为止,我所拥有的最好的想法是在主要文本框之上的另一个文本框,只要搜索文本框获得焦点或文本,该文本框就不可见.

小智 17

此样式将使用background属性和visualbrush显示文本.一旦控件获得焦点,文本就会被删除.

    <TextBox.Style>
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="">
                        <Setter Property="Background">
                            <Setter.Value>
                                <VisualBrush Stretch="None">
                                    <VisualBrush.Visual>
                                        <TextBlock Text="Enter value" Foreground="Gray"/>
                                    </VisualBrush.Visual>
                                </VisualBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="{x:Null}">
                        <Setter Property="Background">
                            <Setter.Value>
                                <VisualBrush Stretch="None">
                                    <VisualBrush.Visual>
                                        <TextBlock Text="Enter value" Foreground="Gray"/>
                                    </VisualBrush.Visual>
                                </VisualBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsFocused}" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <VisualBrush Stretch="None">
                                </VisualBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
Run Code Online (Sandbox Code Playgroud)


小智 7

试试来自Kevin Moore的Bag-o-Tricks的InfoTextBox样本.您可以从http://work.j832.com/2008/01/real-update-to-bag-o-tricks.html下载它