C# WPF:无法在属性元素上设置属性 private TextBlock_caption=new TextBlock(); 公共文本块标题 { 获取{return\u caption;} 设置{u caption=value;} }

C# WPF:无法在属性元素上设置属性 private TextBlock_caption=new TextBlock(); 公共文本块标题 { 获取{return\u caption;} 设置{u caption=value;} },c#,.net,wpf,xaml,properties,C#,.net,Wpf,Xaml,Properties,给我以下错误: 无法设置属性元素的属性 如果我使用: private TextBlock _caption = new TextBlock(); public TextBlock Caption { get { return _caption; } set { _caption = value; } } <l:CustomPanel> <l:CustomPanel.Caption Text="Caption text" FontS

给我以下错误:
无法设置属性元素的属性

如果我使用:

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>

我的TextBlock显示得很好,但它嵌套在另一个TextBlock中,就像这样,它甚至似乎将自己添加到Caption属性之外:

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

正如您可能已经猜到的,如果可能的话,我希望我的代码能够从自定义面板上的XAML设置我的标题属性

我也用DependencyProperty尝试了相同的代码,但没有成功


那么,有谁能帮我解决这个问题吗?

刚刚从我的一位同事那里得到了一个不理想的解决办法。它涉及将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>


我仍然想知道为什么我不能使用前两个选项,所以如果有人知道,请回答:)

我可以解释出什么地方出了问题以及如何解决

首先,

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

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

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

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

虽然我不再需要它了,但我将来可能需要它,所以谢谢你的明确解释。除了,你该怎么说?有人没有考虑清楚这一点,盲目地将其应用于所有属性,甚至不属于它们的属性。
<l:CustomPanel>    
  <l:CustomPanel.Caption>  
    <TextBlock Text="Caption text" FontSize="18" Foreground="White" />   
  </l:CustomPanel.Caption>  
</l:CustomPanel>
public UIElement Content { get { ...
public static readonly DependencyProperty ContentProperty = ...
<Path>
    <MapLayer.Position xmlns="clr-namespace:Microsoft.Maps.MapControl">
        ...
<Path xmlns:map="clr-namespace:Microsoft.Maps.MapControl">
    <map:MapLayer.Position>
        ...