XAML 获取(并绑定到)Maui中元素的当前显示宽度

m1m5dgzv  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(249)

在我的xaml设置中,我有一个标签,它应该 Package 它的文本。它包含在一个边框中,我希望标签的宽度是边框的宽度。我尝试在标签上使用以下绑定来实现这一点:
WidthRequest="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Border}}, Path=Width}"
但这并没有起作用,我怀疑它没有起作用,因为返回的宽度是NaN(我在运行时写出了边框的宽度,它是NaN)。但这让我很困惑,因为我在边框上绑定了正在工作的Flexlayout的宽度。有什么我遗漏的吗?有没有更好的方法来做到这一点?
示例:

<ScrollView Grid.Row="1">
            <FlexLayout BindableLayout.ItemsSource="{Binding DisplayedUserActions}" JustifyContent="Start" Wrap="Wrap" Direction="Row">  
                <BindableLayout.ItemTemplate>
                    <DataTemplate>                      
                         <Border FlexLayout.AlignSelf="Stretch" FlexLayout.Basis="{Binding Source={RelativeSource FindAncestor, AncestorType{x:Type ScrollView}}, Path=Width, Converter={StaticResource WidthToFlexlayoutBasisConverter}}">
                             <Grid RowDefinitions="*,*">
                                  -- more content --
                                  <Label Grid.Row="1" Text="{Binding Title}" LineBreakMode="WordWrap" HorizontalTextAlignment="Center" VerticalOptions="Center" HorizontalOptions="Center" TextColor="Black" Margin="5" WidthRequest="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Border}}, Path=Width}"/>
                             </Grid>
                         </Border>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
            </FlexLayout>
        </ScrollView>
qnzebej0

qnzebej01#

可以使用数据绑定来实现Label和Border的相同宽度。将Border和Label的WidthRequest属性绑定到相同绑定上下文中的TestWidth属性。如下所示:
XAML:

<StackLayout>
        <StackLayout.BindingContext>
            <local:MyViewModel/>
        </StackLayout.BindingContext>

        <Border BackgroundColor="Pink" WidthRequest="{Binding Testwidth}">
            <Label x:Name="lable" Text="test1111111111111111" WidthRequest="{Binding Testwidth}"/>
        </Border>
</StackLayout>

视图模型:

public class MyViewModel : INotifyPropertyChanged
{
    public double testwidth;
    public event PropertyChangedEventHandler PropertyChanged;
    public double Testwidth
    {
        get { return testwidth; }
        set
        {
            if (testwidth != value)
            {
                testwidth = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Testwidth"));
            }
        }
    }
    public MyViewModel() { testwidth= 100; }
}

相关问题