且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在WPF的CustomTemplate中使用网格?

更新时间:2023-11-14 08:59:16

如果我正确理解了您的问题,原因是Button源自ContentControl,ContentControl只能包含1个项目.

不过,它不一定必须是网格,它可以很容易地是StackPanel或可以容纳多个项目的任何控件.
If I have understood your question correctly, the reason is that Button descendss from ContentControl and ContentControl can only contain 1 item.

It doesn''t have to be a grid though, it could as easily be a StackPanel or any control that can hold more than one item.


好吧,我建议您使用一个边框而不是一个矩形.矩形只是一个形状,而边框是一个容器,因为它继承了Controls.Decorator类.
在此边框中,可以将ContentPresenter放置在其中,而无需网格来固定它.您不能对Rectangle进行相同的操作,因为它不能容纳元素.

因此,您可以像这样创建边框:

Well i would suggest you to use a Border instead of a Rectangle. Rectangle is just a shape but a Border is a container as it inherits the Controls.Decorator class.
In this a Border can place the ContentPresenter inside it without the need for a Grid to hold it. You cannot do the same with a Rectangle as it cannot hold elements.

So you can create a Border like this :

<ControlTemplate TargetType="{x:Type Button}">
<border name="ButtonBorder" cornerradius="4" borderthickness="1">
   <contentpresenter content="{TemplateBinding Content}">
      VerticalAlignment="Center"
      HorizontalAlignment="Center"/>
</contentpresenter></border>



您可以在我的博客中查看:圆形按钮 [ ^ ].

我想补充的一件事是,矩形"将仅为您的Button提供一个形状,而ContentPresenter将显示Button的实际内容.
例如:



You can check it out here in my blog : Round-Edged Button[^].

One more thing i would like to add is that, the Rectangle will only give a shape to your Button but the ContentPresenter will display the actual content of the Button.
For Ex:

<Button Name="myButton" HorizontalAlignment="Center">
   <Button.Content>
       <Image Source="Winter.jpg"/>
   </Button.Content>
</Button>



如果要在按钮中显示此图像,则在模板中,必须设置



If you want to display this Image in your Button, then in Template, you have to set the

<contentpresenter content="{TemplateBinding Content}" />



希望我能解决您的疑问.



I hope i was able to clear your doubt.