【发布时间】:2021-05-28 13:04:53
【问题描述】:
我想在我的自定义视图中声明一个可绑定属性并将其链接到相应的视图模型。
我使用 MVVM 模式并希望将 ui 逻辑和数据逻辑彼此分离。所以我将我的状态和其他数据保留在 viewmodel 中,并根据 viewmodel 数据的变化更新我的视图。
这当然应该通过数据绑定来完成。
假设我得到了以下 xaml ...
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:MyApp.Views.Controls"
x:Class="MyApp.Views.Controls.MyView"
x:DataType="controls:MyViewVm">
<!--TODO: Content-->
</ContentView>
...后面有这段代码...
using System.Runtime.CompilerServices;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MyApp.Views.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyView : ContentView
{
public static readonly BindableProperty StatusProperty = BindableProperty.Create(nameof(Status), typeof(MyStatus), typeof(MyView));
public MyStatus Status
{
get => (MyStatus)GetValue(StatusProperty);
set => SetValue(StatusProperty, value);
}
public MyView()
{
InitializeComponent();
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
switch (propertyName)
{
case nameof(Status):
// TODO: Do styling ...
break;
}
}
}
}
...以及这个视图模型和状态枚举:
namespace AbrechnungsApp.Views.Controls
{
public class MyViewVm : ViewModelBase
{
public MyStatus Status { get; set; }
}
public enum MyStatus
{
Enabled,
Disabled,
Readonly
}
}
现在的问题是:
如何将我的viewmodels Status property 链接到我的views Status bindable property?
【问题讨论】:
-
您需要首先在您的 VM 上实施 INotifyPropertyChanged。看看here 的例子,这可能是什么样子。
-
是的,当然。我忘记了这一点,但在我的实际项目中,我已经实现了这个东西。我会添加它。但这不是问题,绑定工作正常,我只是不知道如何绑定到视图模型。
标签: xaml xamarin.forms bindableproperty