How do I get the width of a custom control from within its own class?
I'm creating a custom RangeSlider
with a track, an overlapping range and two thumbs to change the range. In XAML
, I am able to get the width property of the custom RangeSlider
by binding the reference. In my own case, the label text attribute outputs 352 which is the width of the RangeSlider
. I want to use this width to perform calculations, mainly to determine the width of the range and the position of both thumbs at the endpoints of this range.
<ContentPage xmlns:controls="clr-namespace:NewProject1.Controls"
...
.../>
<VerticalStackLayout HorizontalOptions="Center"
VerticalOptions="Center">
<Label Text="{Binding Source={x:Reference RangeSlider}, Path=Width}"/>
<controls:RangeSlider x:Name="RangeSlider"/>
</VerticalStackLayout>
</ContentPage>
How do I get this width property from within the custom RangeSlider
controls class itself, for example, to calculate the width of the range element?
namespace NewProject1.Controls;
public class RangeSlider : ContentView {
private Border Track = new Border
{
BackgroundColor = Colors.LightGray,
StrokeThickness = 0,
HeightRequest = 2,
ZIndex = 1
};
private Border Range = new Border
{
BackgroundColor = Colors.DarkGray,
StrokeThickness = 0,
HeightRequest = 2,
ZIndex = 2
};
private Border LeftThumb = new Border
{
BackgroundColor = Colors.Black,
StrokeShape = new Ellipse(),
StrokeThickness = 0,
HeightRequest = 12,
WidthRequest = 12,
ZIndex = 3
};
private Border RightThumb = new Border
{
BackgroundColor = Colors.Black,
StrokeShape = new Ellipse(),
StrokeThickness = 0,
HeightRequest = 12,
WidthRequest = 12,
ZIndex = 4
};
public RangeSlider()
{
this.Content = new Grid
{
Children =
{
Track,
Range,
LeftThumb,
RightThumb
},
Padding = new Thickness(16, 3)
};
/**
* My attempts to get the width of this custom control:
*/
Range.WidthRequest = this.Width;
Range.WidthRequest = this.Content.Width;
}
/**
* Pan gesture handling...
* Bindable properties...
* etc. etc. etc.
*/
}
Or, if applicable, is there a better way to calculate the positions?
The width is not calculated at the time the constructor is created so I suggest you to use OnSizeAllocated
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
Range.WidthRequest = width;
}