通过xaml创建带有某些属性的自定义控件
本文关键字:属性 自定义控件 xaml 创建 通过 | 更新日期: 2023-09-27 18:09:38
我创建了一个自定义控件,派生自UserControl,它有一个文本块,一个文本框和2个按钮,名为pathng。
<Grid>
<!-- some other stuff -->
<TextBlock Name="PathName">Name</TextBlock>
</Grid>
我试图设置TextBlock的文本通过外部xaml调用这个控件
<Grid>
<local:PathMng>NameHere</local:PathMng>
</Grid>
但是我不明白我该怎么做才能将文本"NameHere"绑定到TextBlock上。
我试着用"自定义xaml","模板xaml"或可能是太多通用的词来搜索,但我找不到我需要的
提前感谢您的帮助
首先,为了让您更简单,使用如下方式设置它,例如:
<local:PathMng MyText="NameHere"/>
现在,在你的用户控制代码后面,创建一个依赖属性:
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(UserContrrol1), new PropertyMetadata(null));
最后,在UserControl1 XAML中,将TextBox的Text属性绑定到DP:
<TextBox Text="{Binding MyText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}}}" />
所有这些都假设您的用户控件名为UserControl1