【问题标题】:Binding text via a function通过函数绑定文本
【发布时间】:2016-11-01 10:53:11
【问题描述】:

我正在使用 Xamarin 开发一个应用程序,目前正在尝试将屏幕宽度显示为(我稍后计划以此为基础确定某些对象的大小)

我正在尝试使用绑定来执行此操作,但不幸的是它似乎没有按预期工作。它不会抛出异常,只是我尝试绑定的标签没有文本值。

我确信在项目的其余部分我会大量使用绑定,所以我非常感谢任何建议。

请考虑以下代码:

C#:

using Xamarin.Forms;
using XLabs.Ioc;
using XLabs.Platform.Device;

namespace TimerStyles
{
    public partial class SavedTimesPage : ContentPage
    {
        string screenWidthText = "";

        public SavedTimesPage()
        {
            InitializeComponent();
            this.screenWidth = getScreenWidth();
        }

        public string screenWidth
        {
            protected set
            {
                screenWidthText = value;
            }
            get { return screenWidthText; }
        }

        public string getScreenWidth()
        {
            var dev = Resolver.Resolve<IDevice>();
            var display = dev.Display;
            double ScreenWidthInches = (double)display.Width / display.Xdpi;
            var ScreenWidth = (ScreenWidthInches.ToString());

            return ScreenWidth;
        }

        public string getScreenHeight()
        {
            var dev = Resolver.Resolve<IDevice>();
            var display = dev.Display;
            double ScreenHeightInches = (double)display.Height / display.Ydpi;
            var ScreenHeight = (ScreenHeightInches.ToString());

            return ScreenHeight;
        }
    }
}

Xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:TimerStyles="clr-namespace:TimerStyles;assembly=TimerStyles"
             x:Class="TimerStyles.SavedTimesPage"
             NavigationPage.HasNavigationBar="false">

  <ContentPage.Content>  
    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="#232224">
      <Label Text="x" TextColor="Blue" FontSize="Large"/>
      <Label Text="{Binding screenWidth}" TextColor="Blue" FontSize="Large"/>
      <Label Text="x" TextColor="Blue" FontSize="Large"/>

    </StackLayout>   
  </ContentPage.Content> 

</ContentPage>

【问题讨论】:

  • 你指定了 BindingContext 吗?
  • 我对此表示怀疑,如何做到这一点?
  • 谢谢你的链接,我现在正在浏览它。在标签元素上添加绑定数据是否正确?如果是这样,应该设置什么,我试过 SavedtimesPage 但是唉,它在运行时抛出一个未处理的异常

标签: c# wpf xaml xamarin


【解决方案1】:

通过创建一个“view-model”类作为视图和模型之间的中介来解决这个问题,如下链接所示:

https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_bindings_to_mvvm/

(通过进一步关注 cristallo 在 cmets 中给出的链接获得)

希望这将帮助太空时代未来遇到同样问题的任何人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 2016-04-24
    • 2011-09-11
    • 2014-09-18
    • 2013-08-22
    • 1970-01-01
    • 2016-10-11
    • 2011-02-25
    相关资源
    最近更新 更多