我正在 WPF 中创建一个简单的用户控件,其中包含一个按钮内的 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
像下面这样,那么restart视觉工作室:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButton),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.AffectsRender));
MSDN 文档 https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkpropertymetadataoptions?view=netframework-4.7 about FrameworkPropertyMetadataOptions.AffectsRender
says
渲染或布局组合的某些方面(除了测量或
排列)受此依赖属性的值更改的影响。
对于其他情况,还有 AffectsMeasure、AffectsArrange 等选项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)