Skip to main content
 首页 » 编程设计

c#之如何在控件模板中获取目标的属性值

2024年02月13日13zlslch

假设我有以下内容:

<ControlTemplate x:Key="MyButtonTemplate" TargetType="{x:Type Button}"> 
   <Grid> 
      <Rectangle Width="100" Height="20" /> 
   </Grid> 
</ControlTemplate> 
 
<Button Template="MyButtonTemplate" Width="25" /> 
<Button Template="MyButtonTemplate" Width="50" /> 
<Button Template="MyButtonTemplate" Width="75" /> 

我需要对控件模板做些什么才能使矩形成为按钮的宽度,而不是每次都硬编码 100?有没有办法让我从我的控件模板内部访问我的目标类型的属性值?

谢谢。

请您参考如下方法:

这个怎么样:

 <Rectangle Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" />