簡體   English   中英

綁定到 ControlTemplate 中的屬性不起作用

[英]Binding to a property in ControlTemplate does not work

我有一個帶有 Xamarin.Forms 和 FreshMvvm 的移動應用程序。 每個頁面都使用 App.xaml 中定義的控件模板:

          <ControlTemplate x:Key="MainPageTemplate">
            <Grid BindingContext="{Binding Source={RelativeSource TemplatedParent}}">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="9*" />
                </Grid.RowDefinitions>
                <Image Source="{local:ImageResource MyApp.Images.My_logo.jpg}" Margin="0, 0, 0, 5" Grid.Row="0" />
                <Label Text="{Binding ScreenName}" FontSize="Subtitle" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Center" Grid.Row="1" />
                <Label Text="{Binding ErrorMessage}" TextColor="Red" Grid.Row="2" />
                <ContentPresenter Margin="10, 0, 10, 10" Grid.Row="3" />
            </Grid>
        </ControlTemplate>

ScreenName 屬性在 PageModel 中定義如下:

        protected string _screenName;

        public string ScreenName => _screenName;

由於某種原因,屏幕名稱未顯示在使用控件模板的頁面上。 如果我將 Binding 替換為硬編碼文本,它就會執行:

<Label Text="Something" ...

BindingContext設置為{RelativeSource TemplatedParent}時,您的綁定上下文就是頁面。

要訪問您的 ViewModel,您必須更改您的 xaml 以通過頁面的“BindingContext”訪問您的屬性。

<Label Text="{Binding BindingContext.ScreenName}" FontSize="Subtitle" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Center" Grid.Row="1" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM