我可以在后面的页面代码中做到这种情况,将参数传递给视图模型构造函数,具体如下。
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编辑器给了我一个警告,如下所示。
这是一个bug还是一个功能?
如果你想设置 BindingContext 在xaml中带参数。你可以检查下面的代码。
<ContentPage.BindingContext>
<local:DateTimeViewModel>
<x:Arguments>
<x:Double>1000</x:Double>
</x:Arguments>
</local:DateTimeViewModel>
</ContentPage.BindingContext>
看起来你绑定了ContentPage的上下文作为ViewModel的一个属性。但它将是更好的绑定整个ViewModel,然后你就可以在页面的任何地方访问它的属性。