【问题标题】:How to properly do data binding in Xamarin Forms?如何在 Xamarin Forms 中正确进行数据绑定?
【发布时间】:2022-09-29 21:53:23
【问题描述】:

我对 Xamarin Forms 非常陌生,而且我非常迷茫。有人可以给我一个使用 MVVM 将主要数据绑定到标签的示例吗?

我目前有InformationPage 的视图InformationPageModel 的视图模型和ResourceGatheringLogic 的模型。

我试图弄清楚如何从嵌入式资源中读取 JSON,但我什至无法正确绑定字符串以显示 HelloWorld 以进行数据绑定。

我只想要一个非常简单的例子来说明如何正确地做到这一点,我很可能会做剩下的。提前谢谢了。

我的.xaml

<ContentPage xmlns=\"http://xamarin.com/schemas/2014/forms\"
             xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"
             xmlns:local=\"clr-namespace:uCue_Game.ViewModel\"
             xmlns:xct=\"http://xamarin.com/schemas/2020/toolkit\"
             x:Class=\"uCue_Game.View.InformationPage\">
    <ContentPage.BindingContext>
        <local:InformationPageModel/>
    </ContentPage.BindingContext>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height=\"1*\"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width=\"1*\"/>
        </Grid.ColumnDefinitions>

        <Frame BackgroundColor=\"LightGreen\"
               VerticalOptions=\"FillAndExpand\"
               HorizontalOptions=\"FillAndExpand\">
            <Label Text=\"{Binding MediaSource}\"
                   TextColor=\"Black\"
                   FontSize=\"20\"
                   FontAttributes=\"Bold\"
                   VerticalOptions=\"CenterAndExpand\"
                   HorizontalOptions=\"CenterAndExpand\"
                   HeightRequest=\"300\"
                   WidthRequest=\"300\"/>
        </Frame>
    </Grid>
    
</ContentPage>

我的.xaml.cs

namespace uCue_Game.View
{
    using Xamarin.Forms;


    public partial class InformationPage : ContentPage
    {
        public InformationPage()
        {
            InitializeComponent();
        }
    }
}

我的 ViewModel .cs 忽略 SetMediaSource 供以后使用。

namespace uCue_Game.ViewModel
{
    using global::Model;
    using Xamarin.Forms;

    public class InformationPageModel
    {
        IMediaSource mediaSource;
        public string MediaSource = \"Hello\";

        public InformationPageModel()
        {
            this.mediaSource = DependencyService.Get<IMediaSource>();
            //SetMediaSource();
        }

        public void SetMediaSource()
        {
            if (mediaSource != null)
                return;

            MediaSource = mediaSource.GetMediaSource();
        }
    }
}
  • 你只能绑定到公共财产. MediaSource 不是 C# 属性

标签: c# xamarin xamarin.forms


【解决方案1】:

你只能绑定到公共财产

public string MediaSource { get; set; } = "Hello";

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2016-11-24
    • 2021-12-17
    • 2017-08-30
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2018-03-09
    相关资源
    最近更新 更多