如何从自定义控件自己的类中获取其宽度?
我正在创建一个RangeSlider
带有轨道、重叠范围和两个拇指来更改范围的自定义。在 中XAML
,我可以RangeSlider
通过绑定引用来获取自定义的宽度属性。就我自己而言,标签文本属性输出 352,这是RangeSlider
.我想用这个宽度来进行计算,主要是确定范围的宽度以及两个拇指在这个范围端点的位置。
<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>
如何从自定义控件RangeSlider
类本身获取此宽度属性,例如,计算范围元素的宽度?
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.
*/
}
或者,如果适用,是否有更好的方法来计算仓位?
创建构造函数时未计算宽度,因此我建议您使用
OnSizeAllocated