【发布时间】:2019-07-18 08:42:30
【问题描述】:
我想在 XAML 的文本视图中获得来自 c# 类的属性。这个怎么做?我想显示用户何时开始工作,结束工作时长(他登录后的每一天)。
这是我的代码:
XAML
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient">
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="@color/colorPrimary"
app:itemIconTint="@drawable/nav_item_color_state"
app:itemTextColor="@drawable/nav_item_color_state"
app:menu="@menu/bottom_navigation_main"
/>
android:text="You're at work since:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_marginTop="84dp"
android:id="@+id/entryTextView"
android:layout_centerHorizontal="true"
android:theme="@style/MyCustomTheme"/>
<TextView
android:text= Today you work already:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_alignParentTop="true"
android:layout_marginTop="226dp"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#ffffff"
android:id="@+id/timeTextView"
android:layout_centerHorizontal="true"
android:theme="@style/MyCustomTheme"/>
我想用 C# 类进行绑定
public LoginViewModel(ILogin login)
{
_loginService = login;
_appVariables = new AppVariables();
GoToDashboard = new Interaction<Unit, Unit>();
var canLogin = this.WhenAnyValue(x => x.UserName, x => x.Password, LoginInputValidator.Validate);
LoginCommand = ReactiveCommand.CreateFromTask(async () => { await TryLogin(); }, canLogin);
}
private async Task<IObservable<bool>> TryLogin()
{
var lg = await _loginService.Login(_userName, _password);
if (lg)
{
_appVariables.UserName = UserName;
_appVariables.logDate = DateTime.Now;
_appVariables.isLogged = true;
await GoToDashboard.Handle(Unit.Default);
}
return Observable.Return(lg);
}
c# 另一个类
public class AppVariables
{
public bool isLogged;
public DateTime logDate;
public DateTime offDate;
public string UserName;
}
这个我试过了
BindingContext = this;
InitializeComponent();
但是总是红,不知道是什么问题。
【问题讨论】:
-
你得到的红色错误是什么?而且您不能在 Xamarin.Android 中使用绑定。 Xamarin.forms 项目中提供数据绑定。
-
无法解析绑定上下文并初始化组件。我有一个单独的类来保持记录的时间和类的实例。我唯一想念的是如何在 xaml 中显示用户当时开始工作的内容。
-
你是在写 xamarin.android 项目还是 xamarin.forms 项目?
-
xamarain.android
-
那么,你能不能在后面的代码中获取 textView 并将 textView 的文本设置为:
TextView textV = FindViewById<TextView>(Resource.Id.timeTextView);然后textV.Text = "Today you work already:" + //the time you want to display
标签: c# android xaml xamarin android-databinding