我正在 WPF 中创建一个简单的用户控件,它在 Button 中包含一个 TextBlock。
<UserControl x:Class="WpfExpansion.MyButton"..... >
<Grid >
<Button Background="Transparent" >
<TextBlock Text="{Binding Path=Text}"/>
</Button>
</Grid>
</UserControl>
还有“文本”依赖属性。
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));
}
然后我像这样使用 UserControl:
<MyButton Text="Test" />
问题是 Visual Studio 设计没有改变,但它在运行时有效。
怎么了?
我也试过
DataContext="{Binding RelativeSource={RelativeSource Self}}"
在 UC 定义中,没有成功。
最佳答案
尝试使用 FrameworkPropertyMetadata
而不是 PropertyMetadata
,如下所示指定 AffectsRender
,然后重新启动 Visual Studio:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButton),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.AffectsRender));
MSDN Documentation关于 FrameworkPropertyMetadataOptions.AffectsRender
说
Some aspect of rendering or layout composition (other than measure or arrange) is affected by value changes to this dependency property.
对于其他情况,有 AffectsMeasure、AffectsArrange 等选项。
关于c# - UserControl 依赖属性设计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18158500/