首页 > 其他分享 >WPF自定义搜索框控件样式

WPF自定义搜索框控件样式

时间:2022-12-18 12:37:24浏览次数:28  
标签:控件 自定义 DependencyProperty object BtnCommand typeof WPF public

效果图
默认
image
焦点触发
image

新建一个用户控件,xaml代码如下:
`

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="15"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="36"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Rectangle Grid.Column="0" Grid.ColumnSpan="3" Stroke="White" Fill="Transparent" Height="35" RadiusX="10" RadiusY="10" Opacity="0.8"></Rectangle>
    <TextBox x:Name="TbxInput"  Grid.Column="1"  Background="Transparent" Height="35" KeyDown="TbxInput_OnKeyDown" >
        <TextBox.Template>
            <ControlTemplate TargetType="TextBox">
                <Grid>
                    <TextBlock x:Name="Uc_TblShow" Text="{Binding ElementName=MyControl,Path=PreviewTxt}"  Foreground="White" Opacity="0.5" VerticalAlignment="Center" Visibility="Collapsed"></TextBlock>
                    <TextBox x:Name="Uc_TbxContent" Width="250" Style="{StaticResource NormalTextBox}" Foreground="White" Background="Transparent"  VerticalAlignment="Center" VerticalContentAlignment="Center" BorderThickness="0"
                             Text="{Binding ElementName=TbxInput,Path=Text,Mode=TwoWay}" FontSize="18"></TextBox>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger SourceName="Uc_TbxContent" Property="Text" Value="">
                        <Setter TargetName="Uc_TblShow" Property="Visibility" Value="Visible"></Setter>
                    </Trigger>
                    <Trigger SourceName="Uc_TbxContent" Property="IsFocused" Value="True">
                        <Setter TargetName="Uc_TblShow" Property="Visibility" Value="Collapsed"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </TextBox.Template>
    </TextBox>
    <Button x:Name="BtnSearch" Grid.Column="2" Click="BtnSearch_OnClick" Cursor="Hand">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Label x:Name="Uc_Image" Style="{StaticResource NormalLabel}" VerticalContentAlignment="Center" Content="&#xf002;" Height="35" Width="35"></Label>
                    <ContentPresenter></ContentPresenter>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="Uc_Image" Property="Height" Value="25"></Setter>
                        <Setter TargetName="Uc_Image" Property="Width" Value="25"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>`

后台代码:
`

public partial class SearchTextBox : UserControl
{
    public SearchTextBox()
    {
        InitializeComponent();
     
    }
    public ICommand BtnCommand
    {
        get { return (ICommand)GetValue(BtnCommandProperty); }
        set { SetValue(BtnCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BtnCommandProperty =
        DependencyProperty.Register("BtnCommand", typeof(ICommand), typeof(SearchTextBox), new PropertyMetadata(default));



    public object CommandParameter
    {
        get { return (object)GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CommandParameter.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.Register("CommandParameter", typeof(object), typeof(SearchTextBox), new PropertyMetadata(default));



    public string PreviewTxt
    {
        get { return (string)GetValue(PreviewTxtProperty); }
        set { SetValue(PreviewTxtProperty, value); }
    }

    // Using a DependencyProperty as the backing store for PreviewTxt.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PreviewTxtProperty =
        DependencyProperty.Register("PreviewTxt", typeof(string), typeof(SearchTextBox), new PropertyMetadata("输入"));

   
    public event EventHandler<SearchEventArgs> OnSearch;
    private void BtnSearch_OnClick(object sender, RoutedEventArgs e)
    {
        if (this.BtnCommand != null)
        {
            this.BtnCommand.Execute(TbxInput.Text);
        }
        ExeccuteSearch();
    }

    private void TbxInput_OnKeyDown(object sender, KeyEventArgs e)
    {
        ExeccuteSearch();
    }

    private void ExeccuteSearch()
    {
        if (OnSearch != null)
        {
            var args = new SearchEventArgs();
            args.SearchText = TbxInput.Text;
            OnSearch(this, args);
        }
    }
}
public class SearchEventArgs : EventArgs
{
    public string SearchText { get; set; }
}`

其中

  • PreviewTxt属性用来设置搜索框的默认提示文字,类似PlaceHolder属性。
  • BtnCommand用来对外绑定ViewModel中的Command,点击按钮触发Click事件时执行Command

默认将输入的搜索内容作为Command命令参数,因此外部调用控件时,不需要再传递参数。

画面中调用控件方式如下:
<controls:SearchTextBox DockPanel.Dock="Right" Width="300" PreviewTxt="输入接口名称/描述" Command="{Binding XXXCommand}" Margin="0 0 10 0" ></controls:SearchTextBox>

标签:控件,自定义,DependencyProperty,object,BtnCommand,typeof,WPF,public
From: https://www.cnblogs.com/cyberneo666/p/16990154.html

相关文章

  • [编程基础] C#自定义类调用窗体控件
    如果自定义类需要调用窗体控件,首先需要将窗体控件的可见级别(Modifiers)设为public。如下图所示:然后在Form1类下定义静态变量form1,并初始化。 classForm1:Form{//在For......
  • 编译固件如何加入自定义配置
    编译固件如何加入自定义配置来源 https://forum.gl-inet.cn/forum.php?mod=viewthread&tid=143参考https://github.com/JiaY-shi/build-gl.inet参考  https://githu......
  • 【libsvm】使用与自定义核函数
    一、svmtrain.c部分voidexit_with_help(){mexPrintf("Usage:model=svmtrain(training_label_vector,training_instance_matrix,'libsvm_options');\n"......
  • 自定义注解使用在AOP切面编程里
    自定义注解:@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public@interfaceRedisDistributeLock{Stringkey();intleastLockMs()......
  • springboot配置自定义objectMapper
      packagecom.my.config;importcom.fasterxml.jackson.annotation.JsonInclude;importcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackso......
  • 【云原生】Prometheus 自定义告警规则
    目录一、概述二、告警实现流程三、告警规则1)告警规则配置1)监控服务器是否在线3)告警数据的状态四、实战操作1)下载node_exporter2)启动node_exporter3)配置Prometheus加载nod......
  • springboot启动读取配置文件过程&自定义配置文件处理器
        最近看到看到spring的配置文件放在了resources/config/application.yal文件内部,第一次见。就想的研究下,springboot启动读取配置文件的过程。1.启动过程org.spring......
  • wpf GridView去除右侧空白列
    页面<ListViewSizeChanged="ListView_SizeChanged"Loaded="ListView_Loaded"><ListView.View><GridView><GridViewColumnHeader="col1"Width=......
  • <三>自定义删除器
    unique_ptr的成员函数在上一篇博客中几乎全部涵盖,其实还有一个很有踢掉,即std::unique_ptr::get_deleter字面已经很明显了,就获得deleter智能指针采通过引用计数我们能解决......
  • 【SpringBoot】封装自定义的starter
    一、参考资料​​SpringBoot封装自己的Starter-码农教程​​​​[Gradle]发布构件到本地仓库​​​​Gradle插件之maven-publish:发布androidlibrary到maven仓库-知乎......