[英]UserControl Dependency Property design time
我正在 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
如下,然后重新启动Visual Studio:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButton),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.AffectsRender));
关于FrameworkPropertyMetadataOptions.AffectsRender
MSDN 文档说
渲染或布局组合的某些方面(度量或排列除外)受此依赖属性的值更改的影响。
对于其他情况,还有 AffectsMeasure、AffectsArrange 等选项。
金铲候选人,我仍然遇到了同样的问题,并在https://www.codeproject.com/Questions/1096567/How-to-set-a-custom-dependency-property-of-user-的启发下解决了它合作
长话短说:您的依赖属性设置在UserControl
本身上,您正试图将其子属性绑定到它。 子绑定需要定义RelativeSource
,因此TextBlock
应如下所示:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=Text}" />
唯一需要的DataContext
分配是您在构造函数后面的代码中已有的分配。
DataContext
,则不需要在每个控件中都提供它。
这意味着您需要通过以下方式定义您的 UC( d:DataContext=...
可以解决问题):
<UserControl x:Class="WpfExpansion.MyButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:YRS100_Data_Analysis" mc:Ignorable="d" d:DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <Button Background="Transparent"> <TextBlock Text="{Binding Path=Text}" /> </Button> </Grid> </UserControl>
像魅力一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.