如何创建宽度和高度均匀的按钮?

时间:2011-07-21 04:07:36

标签: wpf button styles

我想创建一个按钮,其大小是它最大的边缘。

原因是我希望该按钮是嵌入DataGrid列内的小信息圈。

目前我有:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Content="i" Padding="2" Margin="0"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center"
                    Width="{Binding Source=Self, Path=Height}">
                <Button.Template>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Ellipse Fill="#FFF4F4F5" Stroke="#FF6695EB"/>
                            <ContentPresenter Margin="0"
                                              RecognizesAccessKey="False"
                                              SnapsToDevicePixels="True"
                                              VerticalAlignment="Center"
                                              HorizontalAlignment="Center"
                                              />
                        </Grid>
                    </ControlTemplate>
                </Button.Template>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

2 个答案:

答案 0 :(得分:2)

创建一个派生自Button的类并覆盖Measuring,例如

public class SquareButton : Button
{
    protected override Size MeasureOverride(Size constraint)
    {
        Size size = base.MeasureOverride(constraint);
        size.Height = size.Width = Math.Max(size.Height, size.Width);
        return size;
    }
}

然后您可以使用以下内容:

<local:SquareButton 
    Content="i" Padding="2" Margin="0"
    VerticalAlignment="Center"
    HorizontalAlignment="Center">
    <local:SquareButton.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid>
                <Ellipse Fill="#FFF4F4F5" Stroke="#FF6695EB"/>
                <ContentPresenter Margin="0"
                    RecognizesAccessKey="False"
                    SnapsToDevicePixels="True"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center"
                    />
            </Grid>
        </ControlTemplate>
    </local:SquareButton.Template>
</local:SquareButton>

答案 1 :(得分:1)

制作自定义控件 - SquareButton

public class SquareButton : Button
{
    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        if (e.Property == HeightProperty || e.Property == WidthProperty)
            this.Height = this.Width = Math.Max(this.Width, this.Height);

        base.OnPropertyChanged(e);
    }
}