我創建了一個名爲InfoBox的UserControl,它像一個花哨的文本塊(額外的按鈕等)。它工作正常。我可以混合使用它像這樣:將TextBlock或內聯集合傳遞給WPF中的子控件UserControl
<myNS:InfoBox Text="Some Text"/>
,其中「文本」是一個依賴屬性:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(InfoBox),
new UIPropertyMetadata(null,ValueChanged));
和處理,像這樣:
private static void ValueChanged(DependencyObject dpo,
DependencyPropertyChangedEventArgs args)
{
((InfoBox)dpo).TextBlock.Text = (string)args.NewValue;
}
當我在添加控件Blend,它會顯示它的設計時間示例文本,直到我指定Text =「Something」,在這種情況下,「Something」奇蹟般地出現在設計器中。完善!
但是現在我想傳遞的不僅僅是文本,我希望能夠使用與textblock內聯的所有時髦功能。運行,斜體等...
爲什麼下面不起作用?
<myNS:InfoBox>
<myNS:InfoBox.ReferenceBlock>
<TextBlock>
<Run Language="en-gb" Text="SampleSample"/><LineBreak/>
<Run Language="en-gb"/><LineBreak/>
<Run Language="en-gb" Text="MoreMoreMore"/>
</TextBlock>
<myNS:InfoBox.ReferenceBlock>
</myNS:InfoBox>
。
public static readonly DependencyProperty ReferenceBlockProperty =
DependencyProperty.Register("ReferenceBlock", typeof(TextBlock),
typeof(InfoBox), new UIPropertyMetadata(null, ReferenceBlockReceived));
[...]
private static void ReferenceBlockReceived(DependencyObject dpo,
DependencyPropertyChangedEventArgs args)
{
var textblock = (TextBlock)args.NewValue;
if (textblock != null)
{
((InfoBox)dpo).TextBlock.Inlines.Clear();
((InfoBox)dpo).TextBlock.Inlines.AddRange(textblock.Inlines);
}
}
處理程序收到的TextBlock由於某種原因完全是空的。我感謝任何幫助。這WPF的東西很難!
我不是真的想重現行爲,而是將一個實例或textblock實例的副本傳遞給我的控件。不知道爲什麼這是不可能的?無論如何,我會看看dotpeek,謝謝 – 2012-02-26 21:50:19