Avalonia TemplatedControl (模板控件)

在ava中的模板控件相当于wpf中的自定义控件

在下面示例中,将绘制一个文本框和一个按钮,用来组合一个搜索控件

在app.axaml中加入样式

<Application.Styles>
<FluentTheme />
<StyleInclude Source="/TemplatedControl1.axaml" />
</Application.Styles>

引入并使用

xmlns:local="using:AvaloniaApplication2"
<local:TemplatedControl1 />

为控件定义搜索文字属性

public static readonly StyledProperty<string> SearchTextProperty =
AvaloniaProperty.Register<TemplatedControl1, string>(nameof(SearchText), defaultValue: "");
public string SearchText
{
get => GetValue(SearchTextProperty);
set => SetValue(SearchTextProperty, value);
}

在前台使用

<local:TemplatedControl1 SearchText="百度一下" />

毫无效果,在样式中将他们关联

查看效果

为控件定义搜索事件
在模板中为按钮添加名字

private Button btnSearch;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
//根据模板内的名字找到控件
btnSearch = e.NameScope.Find<Button>("btnSearch");
btnSearch.Click += (s, e) =>
{
//在内部按钮的事件中,执行外部注册的 OnSearch 事件
RoutedEventArgs args = new RoutedEventArgs(OnSearchEvent);
RaiseEvent(args);
};
}
public static readonly RoutedEvent<RoutedEventArgs> OnSearchEvent =
RoutedEvent.Register<TemplatedControl1, RoutedEventArgs>(nameof(OnsSearch), RoutingStrategies.Direct);
public event EventHandler<RoutedEventArgs> OnsSearch
{
add => AddHandler(OnSearchEvent, value);
remove => RemoveHandler(OnSearchEvent, value);
}

这样即可在外部注册事件

public MainWindow()
{
InitializeComponent();
searchCtrl.OnsSearch += SearchCtrl_OnsSearch;
}
private void SearchCtrl_OnsSearch(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
Debug.WriteLine(searchCtrl.SearchText);
}

在模板中,定义Text属性双向绑定,使文本框输入后属性也更新值

<TextBox Width="120" Text="{TemplateBinding SearchText, Mode=TwoWay}" />
posted @   trykle  阅读(555)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示