WPF自定义搜索框控件样式
效果图
默认

焦点触发

新建一个用户控件,xaml代码如下:
`
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<TextBox.Template>
<ControlTemplate.Triggers>
</ControlTemplate.Triggers>
</TextBox.Template>
后台代码:
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
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>
本文来自博客园,作者:cyberneo666,转载请注明原文链接:https://www.cnblogs.com/cyberneo666/p/16990154.html

浙公网安备 33010602011771号