[英]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.