Can you databind to CornerRadius via WPF Styles?

假如想象 提交于 2019-12-10 23:48:35

问题


I have a Button style and can't seem to property databind the border's CornerRadius property to the template. This is a dependency property, so it should be data bindable. I wonder if I'm missing the right XAML syntax to use?

<Style TargetType="{x:Type Button}" BasedOn="{x:Null}">         
      <Setter Property="FocusVisualStyle" Value="{DynamicResource MyButtonFocusVisual}"/>       
      <Setter Property="Background" Value="{DynamicResource MyButtonBackgroundBrush}"/>       
      <Setter Property="Foreground" Value="{DynamicResource MyButtonForegroundBrush}"/>
      <Setter Property="BorderBrush" Value="{DynamicResource MyButtonBorderBrush}"/>
      <Setter Property="BorderThickness" Value="3"/>
      <Setter Property="FontFamily" Value="Segoe UI"/>      
      <Setter Property="FontSize" Value="14" />
      <Setter Property="CornerRadius" Value="2" />
      <Setter Property="Template">          
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
           <!-- We use Grid as a root because it is easy to add more elements to customize the button -->
           <Grid x:Name="Grid">
           <Border x:Name="Border" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"/> 
           </Grid> 
         </ControlTemplate>             
       </Setter.Value>      
     </Setter>                  
   </Style>

Both and CornerRadius="{TemplateBinding CornerRadius}" give me the error "CornerRadius is not recognized or is not accessible".


回答1:


You're trying to set/bind a CornerRadius property on class Button, but there is no such property. So the error is expected.




回答2:


Kent is right. A way around this is to create your own custom control that inherits from the button class. Then inside this derived class, create a dependency property and register it to the window for the CornerRadius property. Then you may use the above code, but instead of setting the style property on a Button control, set the style property on the derived class.



来源:https://stackoverflow.com/questions/327838/can-you-databind-to-cornerradius-via-wpf-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!