Xamarin Forms控件值不可见

时间:2018-05-03 20:26:36

标签: forms xamarin xamarin.forms

我创建了一个页面,将值传递给允许用户更新数据的新页面。当用户选择要更新的记录时,编辑表单将打开,但数据不可见。如果更改了值并单击了编辑按钮,则会更新该值,但它永远不可见。如何显示要编辑的数据?

查看模型

namespace QiApp.ViewModels
{
    public class EditTodayCasesViewModel
    {
        private SxCaseDataService _sxCaseDataService = new SxCaseDataService();

        public SxCase SelectedSxCase { get; set; }

        public ICommand EditSxCaseCommand => new Command(async () =>
            {
               await _sxCaseDataService.PutSxCase(SelectedSxCase.SxCaseId, SelectedSxCase);
            });
    }
}

修改页面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:viewModels="clr-namespace:QiApp.ViewModels;assembly=QiApp.UWP"
             x:Class="QiApp.Views.EditTodayCasePage">
    <ContentPage.BindingContext>
        <viewModels:EditTodayCasesViewModel/>
    </ContentPage.BindingContext>

    <StackLayout>
        <Label Text="Surgery Case"/>
        <Label Text="{Binding SelectedSxCase.SxCaseId}"/>
        <Entry Text="{Binding SelectedSxCase.Record}"/>
        <Switch IsToggled="{Binding SelectedSxCase.Complete}"/>
        <Button Text="Edit Surgery Case"
                Command="{Binding EditSxCaseCommand}"/>
    </StackLayout>
</ContentPage>

代码

namespace QiApp.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class EditTodayCasePage : ContentPage
    {


        public EditTodayCasePage(SxCase sxCase)
        {
            InitializeComponent();

            var editTodayCasesViewModel = BindingContext as EditTodayCasesViewModel;

            editTodayCasesViewModel.SelectedSxCase = sxCase;


        }
    }
}

1 个答案:

答案 0 :(得分:0)

一切都没有问题,只是你的视图绑定到一个视图模型,如果属性被更改,它将保持静默。您的视图无法获取有关何时更新自身以及属性SelectedSxCase更改后的UI的任何信息。

值得庆幸的是,这可以通过简单地实现公共接口INotifyPropertyChanged并使用代码行扩展绑定属性来提高接口提供的事件。

基本上就是这样......

private SxCase _case;
public SxCase SelectedSxCase 
{ 
    get => _case; 
    set
    {
        _case = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedSxCase)));
    }
}

...但有几种实现可以做得更优雅,例如using the CallerMemberName甚至weaving the getter and setter automatically with Fody