簡體   English   中英

How to pass arguments to the view model constructor declared in Xamarin.Forms XAML binding context element?

[英]How to pass arguments to the view model constructor declared in Xamarin.Forms XAML binding context element?

我可以做這個場景,其中我將 arguments 傳遞給視圖 model 構造函數,在后面的頁面代碼中如下。

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged(string propertyName)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public class DateTimeViewModel : ViewModelBase
{
    public DateTimeViewModel(double interval = 15)
    {
        TimeSpan ts = TimeSpan.FromMilliseconds(interval);
        Device.StartTimer(ts, () =>
        {
            DateTime = DateTime.Now;
            return true;
        });
    }

    private DateTime dt = DateTime.Now;

    public DateTime DateTime
    {
        get => dt;
        private set => SetProperty(ref dt, value);
    }
}

public partial class TimerPage : ContentPage
{
    public TimerPage()
    {
        InitializeComponent();
        var myVM = new DateTimeViewModel(1000);
        var itemSourceBinding = new Binding(nameof(myVM.DateTime), source: myVM);
        SetBinding(ContentPage.BindingContextProperty, itemSourceBinding);
    }
}


<ContentPage <!--removed for simplicity--> x:Class="MyProject.TimerPage">
     <StackLayout>
        <Label Text="{Binding Millisecond}" />
     </StackLayout>
</ContentPage>

問題

如何在 XAML 中執行以下操作?

var myVM = new DateTimeViewModel(1000);
var itemSourceBinding = new Binding(nameof(myVM.DateTime), source: myVM);
SetBinding(ContentPage.BindingContextProperty, itemSourceBinding);

更新

這只是一個“重要”的注釋,將來可能對其他人也有用。 我只是按照公認的答案做了,它有效,但 Visual Studio 編輯器給了我如下警告

在此處輸入圖像描述

它是錯誤還是功能?

如果要在 xaml 中使用參數設置BindingContext 您可以檢查以下代碼。

<ContentPage.BindingContext>
    <local:DateTimeViewModel>
        <x:Arguments>
             <x:Double>1000</x:Double>
        </x:Arguments>
     </local:DateTimeViewModel>
</ContentPage.BindingContext>

似乎您將 ContentPage 的綁定上下文綁定為 ViewModel 的屬性。 但是最好綁定整個 ViewModel,然后您可以在頁面的任何位置訪問它的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM