I'm creating a simple User Control in WPF that contains a TextBlock inside a Button.
<UserControl x:Class="WpfExpansion.MyButton"..... >
<Grid >
<Button Background="Transparent" >
<TextBlock Text="{Binding Path=Text}"/>
</Button>
</Grid>
</UserControl>
And also the "Text" dependency property.
public partial class MyButton : UserControl
{
public MyButton()
{
InitializeComponent();
this.DataContext = this;
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButton), new PropertyMetadata(string.Empty));
}
And then I use the UserControl like this:
<MyButton Text="Test" />
The problem is that the Visual Studio design does not change, but it works in runtime.
What is wrong?
I also tried
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Inside the UC definition, without success.
Try using FrameworkPropertyMetadata
instead of PropertyMetadata
, specifying AffectsRender
like below, then restart Visual Studio:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButton),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.AffectsRender));
MSDN Documentation about FrameworkPropertyMetadataOptions.AffectsRender
says
Some aspect of rendering or layout composition (other than measure or arrange) is affected by value changes to this dependency property.
For other cases, there are options like AffectsMeasure, AffectsArrange, etc.
来源:https://stackoverflow.com/questions/18158500/usercontrol-dependency-property-design-time