2012-06-19 239 views
0

我创建了一个自定义的控制,但我不能一个属性绑定到这样的内容:当我创建的控制自定义控件绑定属性

<Style TargetType="control:Pie"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="control:Pie"> 
        <Border 
         Background="{TemplateBinding Background}" 
         BorderBrush="{TemplateBinding BorderBrush}" 
         BorderThickness="{TemplateBinding BorderThickness}"> 

         <ContentControl Content="{Binding Path=Test}"/> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

而且在我的控制

public string Test 
    { 
     get { return (string)GetValue(TestProperty); } 
     set { SetValue(TestProperty, value); } 
    } 
    public static readonly DependencyProperty TestProperty = 
     DependencyProperty.Register(
      "Test", 
      typeof(string), 
      typeof(Pie), 
      new PropertyMetadata(null)); 

在Test属性中设置一个字符串,但在视图中没有任何内容出现...

回答

2

TemplateBinding用于绑定到模板化控件,因此仅在ControlTemplate中有效。上面只有2行已经使用了TemplateBinding作为Background,BorderBrush和BorderThickness。

Binding另一方面绑定到DataContext,这是一个用于从用户获取“业务”相关数据的对象。它应该是你的控件是如何工作的独立的和

作为一个经验法则:如果您在ControlTemplate,使用普通的约束力不具有RelativeSourceElementNameSource集,它通常不应该出现在ControlTemplate或Style。

+0

哦,是的,谢谢! – Peekyou