开发者

How do I create a button that has a uniform width and height?

I would like to create a button whose size is that of it's largest edge.

The reason for this is I want the button to be a small information circle embedded inside a DataGrid column.

Currently I have:

<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"
                                              SnapsToDevicePi开发者_C百科xels="True"
                                              VerticalAlignment="Center"
                                              HorizontalAlignment="Center"
                                              />
                        </Grid>
                    </ControlTemplate>
                </Button.Template>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


Create a class derived from Button and override the Measuring, e.g.

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;
    }
}

You can then use it something like this:

<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>


Make a custom control - 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜