2013-08-24 51 views
4

假設我有一個TextBox控件,並且我想向其添加一個簡單的字符串屬性,而無需創建從常規TextBox控件繼承的新的Textbox控件。那可能嗎?如何向現有類型/控件添加屬性

例如,像:

TextBox tx = new TextBox(); 
// I want something like the following 
// tx.addProperty("propertyname", "properyvalue", typeof(string)); 

是在WPF/C#有這樣的東西,什麼是要做到這一點,而無需創建從常規的TextBox控件繼承的新文本框控件最簡單的方法?

+2

你知道你可以使用標籤屬性來存儲每個控件的任何值嗎?例如tx.Tag =「一些文本」 –

+0

爲什麼你特別*不要*想要使用最簡單和簡單的方法,只是做一個texbox的子類? – Corak

回答

5

您可以創建附加的依賴項屬性,並將其應用於任何類型的控件。例如,對於TextBlock。下面是我的例子:

XAML

<Grid> 
    <TextBlock Name="SampleTextBlock" Width="200" Height="30" 
       Background="AntiqueWhite" Text="Sample TextBlock" 
       local:MyDependencyClass.MyPropertyForTextBlock="TestString" /> 

    <StackPanel Width="100" Height="100" HorizontalAlignment="Left"> 
     <Button Name="GetValueButton" Content="GetValueButton" Click="GetValue_Click" /> 
     <Button Name="SetValueButton" Content="SetValueButton" Click="SetValue_Click" /> 
    </StackPanel> 
</Grid> 

Code behind

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void GetValue_Click(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show(MyDependencyClass.GetMyPropertyForTextBlock(SampleTextBlock)); 
    } 

    private void SetValue_Click(object sender, RoutedEventArgs e) 
    { 
     MyDependencyClass.SetMyPropertyForTextBlock(SampleTextBlock, "New Value"); 

     MessageBox.Show(MyDependencyClass.GetMyPropertyForTextBlock(SampleTextBlock)); 
    } 
} 

public class MyDependencyClass : DependencyObject 
{ 
    public static readonly DependencyProperty MyPropertyForTextBlockProperty; 

    public static void SetMyPropertyForTextBlock(DependencyObject DepObject, string value) 
    { 
     DepObject.SetValue(MyPropertyForTextBlockProperty, value); 
    } 

    public static string GetMyPropertyForTextBlock(DependencyObject DepObject) 
    { 
     return (string)DepObject.GetValue(MyPropertyForTextBlockProperty); 
    } 

    static MyDependencyClass() 
    { 
     PropertyMetadata MyPropertyMetadata = new PropertyMetadata(string.Empty); 

     MyPropertyForTextBlockProperty = DependencyProperty.RegisterAttached("MyPropertyForTextBlock", 
                  typeof(string), 
                  typeof(MyDependencyClass), 
                  MyPropertyMetadata); 
    } 
} 

或者你可以使用屬性Tag,它只是已創建,用於存儲更多的信息。但有時候,這個屬性可能會被其他目標占據,或者因爲他的名字而不能成立。最好用直觀的名字來創建他們的財產,例如:ValueForAnimation,StringId, CanScrolling

+1

我沒有在XAML代碼MyDependencyClass.MyProperty中看到類MyDependencyClass中聲明的任何MyProperty?它不應該是'MyDependencyClass.MyPropertyForTextBlockProperty'嗎? –

+0

@ King King:是的,我很着急忘記重命名Get and Set,我會修復它。感謝您的關注。 –

4

通常,最好的方法是從TextBox控件繼承。與javascript不同,C#是一個statically typed language,所以你不能只是添加這樣的屬性。

由於Textbox控件是一個DependencyObject,所以您也可以使用附加屬性 - 請參閱上面/下面的Anatoliy Nikolaev的回答。這可能會更好,具體取決於您希望如何使用該屬性。

如果您只是想添加一條信息,您可以使用文本框的Tag屬性,該屬性是爲此目的而設計的,可以帶任何對象。如果您想要添加多條信息,可以將Tag屬性設置爲值的字典。

相關問題