2016-02-03 108 views
0

我有一个自定义样式的按钮自定义按钮样式内容属性绑定

<Style x:Key="CustomButton" TargetType="Button"> 
    <Setter Property="BorderBrush" Value="Black"/> 
    <Setter Property="Foreground" Value="White"/> 
    <Setter Property="Content"> 
     <Setter.Value> 
      <Grid> 
       <Ellipse Width="40" Height="20" Fill="Yellow"/> 
       <TextBlock Text="{Binding ****Bind to Content Property on button***}"/> 
      </Grid>    
     </Setter.Value> 
    </Setter> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Button"> 
       <Border> 
        <Border.Background> 
         <SolidColorBrush x:Name="CustomBackground" 
             Color="LightBlue"/> 
        </Border.Background> 

        <ContentPresenter/> 
       </Border>     
      </ControlTemplate>    
     </Setter.Value> 
    </Setter> 
</Style> 

与我Content财产一个复杂的对象。 content财产的价值有TextBlock。是否有可能在TextblockText属性绑定到的Button

<Button Style="{StaticResource CustomButton}" 
       Content="Bound to Textblock in style"/> 

回答

1

Content属性简单地使用TemplateBinding绑定TextBlockTextButtonContent

<Style x:Key="CustomButton" TargetType="Button"> 
     <Setter Property="BorderBrush" Value="Black"/> 
     <Setter Property="Foreground" Value="White"/> 

     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <Border> 
         <Border.Background> 
          <SolidColorBrush x:Name="CustomBackground" 
            Color="LightBlue"/> 
         </Border.Background> 

         <Grid> 
          <Ellipse Width="40" Height="20" Fill="Yellow"/> 
          <TextBlock Text="{TemplateBinding Content}"/> 
         </Grid> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
+0

当我用你的代码示例我得到以下错误:''{DependencyProperty.UnsetValue}'不是Setter上的'System.Windows.Controls.Control.Template'属性的有效值。'这只有当我使用'TemplateBinding'时。 “内容”也不会显示智能感知。只有'name','uid'和'ContentStringFormat' – mrsargent

+0

它在我的最后工作正常!,您没有将ContentPresenter替换为实际内容,是不是? – Usama

+0

重新启动视觉工作室,它的工作。谢谢! – mrsargent