C# 如何将参数传递给Xamarin.Forms XAML绑定上下文元素中声明的视图模型构造函数?
我可以在页面代码中这样做,在这个场景中,我将参数传递给视图模型构造函数,如下所示C# 如何将参数传递给Xamarin.Forms XAML绑定上下文元素中声明的视图模型构造函数?,c#,xamarin.forms,C#,Xamarin.forms,我可以在页面代码中这样做,在这个场景中,我将参数传递给视图模型构造函数,如下所示 public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string prop
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>
更新
这只是一个“重要”的注释,将来可能对其他人也有用。我只是按照公认的答案做了,它是有效的,但是VisualStudio编辑器给了我一个警告,如下所示
这是一个bug还是一个功能?如果您想在xaml中使用参数设置BindingContext。您可以检查以下代码
<ContentPage.BindingContext>
<local:DateTimeViewModel>
<x:Arguments>
<x:Double>1000</x:Double>
</x:Arguments>
</local:DateTimeViewModel>
</ContentPage.BindingContext>
1000
似乎您将ContentPage的绑定上下文绑定为ViewModel的属性。但是最好绑定整个ViewModel,然后您可以在页面的任何位置访问其属性。如果您想在xaml中使用参数设置BindingContext。您可以检查以下代码
<ContentPage.BindingContext>
<local:DateTimeViewModel>
<x:Arguments>
<x:Double>1000</x:Double>
</x:Arguments>
</local:DateTimeViewModel>
</ContentPage.BindingContext>
1000
似乎您将ContentPage的绑定上下文绑定为ViewModel的属性。但是最好绑定整个ViewModel,然后您可以在页面的任何位置访问其属性。这是IDE的问题。忽略它并生成您的项目。我会尽快报告:)好的。多谢各位(谢谢)!这是IDE的问题。忽略它并生成您的项目。我会尽快报告:)好的。多谢各位(谢谢)!