首页 > 解决方案 > Xamarin.Forms。如何在后面的代码中调用从项目源创建的 xaml 元素的方法?

问题描述

在这种情况下如何调用 InvalidateSurface 方法?此方法不引用可绑定对象,而是引用 xaml 元素本身。我是应用程序开发的新手,我真的需要弄清楚这一点。

我的 xaml 文件的一部分

<StackLayout>
        <ListView
        CachingStrategy="RecycleElement"
        HasUnevenRows="True"
        ItemsSource="{Binding TheoryContentList}"
        SelectionMode="None"
        SeparatorVisibility="None"
        x:Name="listView">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="model:Wrapper">
                    <ViewCell>
                        <StackLayout>
                            <ScrollView>
                                <math:TextView x:Name="textView" LaTeX="{Binding Formula}" FontSize="{Binding Source={x:Reference TheoryPage1},Path=BindingContext.FSize}" HeightRequest="{Binding HeightReq}"/>
                            </ScrollView>
                            <Label LineBreakMode="WordWrap" HeightRequest="{Binding LabelHeightReq}" HorizontalTextAlignment="End" Margin="15, 0">
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="{Binding BoldText}" FontAttributes="Bold"/>
                                        <Span Text="{Binding Text1}" FontSize="Small" FontAttributes="Italic"/>
                                        <Span x:Name="{Binding }" Text="{Binding Link.Text}" FontSize="Small" TextDecorations="Underline" FontAttributes="Italic" TextColor="Blue">
                                            <Span.GestureRecognizers>
                                                <TapGestureRecognizer Command="{Binding Source={x:Reference TheoryPage1},Path=BindingContext.LinkTappedCommand}" CommandParameter="{Binding Link}"/>
                                            </Span.GestureRecognizers>
                                        </Span>
                                        <Span Text="{Binding Text2}"/>
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Label x:Name="linkLabel" FontSize="Small" TextColor="Gray" Padding="0" Margin="15,0" HorizontalTextAlignment="Start"/>
    </StackLayout>

我的代码在后面

public TheoryPage()
{
    InitializeComponent();
    BindingContext = _viewModel = new TheoryViewModel();
    textView.InvaludateSurface();
}

标签: xamlxamarinxamarin.formsdata-binding

解决方案


为了解决这个问题,我使用了一个包装类:

public class MyTextView : TextView
{
    public MyTextView()
    {
        InvalidateSurface();
    }
}

并在 xaml 文件中使用了这个类:

<views:MyTextView x:Name="textView" LaTeX="{Binding Formula}" Margin="15, 5"/>

推荐阅读