2009-10-12 113 views
10
private TextBlock _caption = new TextBlock(); 

public TextBlock Caption 
{ 
    get { return _caption; } 
    set { _caption = value; } 
} 

<l:CustomPanel> 
    <l:CustomPanel.Caption Text="Caption text" FontSize="18" Foreground="White" /> 
</l:CustomPanel> 

使我有以下错误:
不能设置属性元素的属性。WPF:在属性元素不能设置属性的怪事

如果我使用:

<l:CustomPanel> 
    <l:CustomPanel.Caption> 
     <TextBlock Text="Caption text" FontSize="18" Foreground="White" /> 
    </l:CustomPanel.Caption> 
</l:CustomPanel> 

我的TextBlock显示了罚款,但它嵌套像这样的另一个TextBlock的INSIDE公司的,它甚至似乎将自身添加Caption属性之外:

<l:CustomPanel> 
    <l:CustomPanel.Caption> 
     <TextBlock> 
      <InlineUIContainer> 
       <TextBlock Text="Caption text" FontSize="18" Foreground="White" /> 
      </InlineUIContainer> 
     </TextBlock> 
    </l:CustomPanel.Caption> 

    <TextBlock> 
     <InlineUIContainer> 
      <TextBlock Text="Caption text" FontSize="18" Foreground="White" /> 
     </InlineUIContainer> 
    </TextBlock> 
</l:CustomPanel> 

正如你可能已经猜到的那样,我希望我的代码做的是在自定义面板上将XAML中的Caption属性设置为可能。

我也试过相同的代码与DependencyProperty无济于事。

那么,任何人都可以帮助我解决这个问题?

回答

12

我可以解释发生了什么问题以及如何解决问题。

首先,

<l:CustomPanel> 
    <l:CustomPanel.Caption Text="Caption text" FontSize="18" Foreground="White" /> 

是一个简单的语法错误。 <l:CustomPanel.Caption>语法不接受XML属性 - 属性值必须位于元素内。

这是正确的属性元素语法:

<l:CustomPanel>  
    <l:CustomPanel.Caption> 
    <TextBlock Text="Caption text" FontSize="18" Foreground="White" /> 
    </l:CustomPanel.Caption> 
</l:CustomPanel> 

但:

  1. 属性元素语法仅适用于DependencyProperties(所以也没跟你的CLR属性工作)和
  2. 物业元素语法总是尊重属性类型的ContentPropertyAttribute

由于TextBlock具有[ContentPropertyAttribute(“Inlines”)],因此属性元素语法尝试将TextBlock添加到Inlines集合中。

解决方法很简单:你的声明财产型的DependencyProperty的UIElement,而不是类型TextBlock的。这具有额外的优点,即不会将内容的显示限制为TextBlock。如果你真的想限制它只是一个TextBlock,你可以使用验证回调。

public UIElement Content { get { ... 
public static readonly DependencyProperty ContentProperty = ... 
+0

THX雷,那工作:)虽然我并不需要它了,我可能需要在将来的,所以谢谢为了明确的解释。 – Willy 2010-05-17 06:58:49

+0

除了,你应该怎么说?有人没有考虑到这一点,并盲目地将其应用于* all *属性,即使是不属于它们的属性。 – 2017-02-12 21:54:23

2

刚刚从我的一位同事那里得到了一个不理想的解决方法。它涉及声明Caption属性作为一种资源,如:

<Page.Resources> 
    <TextBlock x:Key="test" Text="Caption text" FontSize="18" Foreground="White" /> 
</Page.Resources> 

<l:CustomPanel Caption="{StaticResource test}" /> 

我还是想知道为什么我不能使用前两个选项,因此,如果有人知道请回答。 :)

0

如果您在元素上指定命名空间,您似乎可以得到此错误(至少在Silverlight 4和5中)。例如:

<Path> 
    <MapLayer.Position xmlns="clr-namespace:Microsoft.Maps.MapControl"> 
     ... 

在这种情况下,MapLayer.Position是一个附加属性。看来,Silverlight的分析器要求使用前缀来定义的命名空间:

<Path xmlns:map="clr-namespace:Microsoft.Maps.MapControl"> 
    <map:MapLayer.Position> 
     ...