我可以在样式中创建自己的属性吗?

问题描述:

我想以一种风格适当地创造我自己,这可能吗?我可以在样式中创建自己的属性吗?

我有foliwing风格

<Style x:Key="EditTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> 
    <Setter Property="TextWrapping" Value="Wrap"/> 
    <Setter Property="AcceptsReturn" Value="True"/> 
    <Setter Property="VerticalScrollBarVisibility" Value="Auto"/> 
</Style> 

,我想添加一个名为“操作”属性...

任何人都知道,如果这是可能的吗?

+0

AFAIK,这是不可能的。但是你可以使用其他现有的属性,比如'Tag'或'DataContext'。 –

+0

感谢Benoit Blanchon –

+0

@BenoitBlanchon你可以使用附加属性来做到这一点 – Loetn

如果你想另一个属性添加到“文本框”你需要扩展类,例如:

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编辑它,并且对象属性是这样你可以acc从C#中获取它。