如果要向“文本框”添加另一个属性,则需要扩展该类,例如:
public class CustomTextBox : TextBox
{
public static readonly DependencyProperty OperationProperty =
DependencyProperty.Register(
"Operation", //property name
typeof(string), //property type
typeof(CustomTextBox), //owner type
new FrameworkPropertyMetadata("Default value")
);
public string Operation
{
get
{
return (string)GetValue(OperationProperty);
}
set
{
SetValue(OperationProperty, value);
}
}
}
然后您可以设置自定义文本框样式:
<Style x:Key="EditTextBox" TargetType="{x:Type CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Operation" Value="string value"/>
</Style>
或者
<my:CustomTextBox Operation="My value" Text="You can still use it as a textbox" />
DependencyProperty 是为了让您可以从 XAML 编辑它,而 object 属性是为了让您可以从 C# 访问它。