您可以創建附加的依賴項屬性,並將其應用於任何類型的控件。例如,對於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
等
你知道你可以使用標籤屬性來存儲每個控件的任何值嗎?例如tx.Tag =「一些文本」 –
爲什麼你特別*不要*想要使用最簡單和簡單的方法,只是做一個texbox的子類? – Corak