本文講述如何實現(xiàn)控件的屬性如何可以被 Binding
官方例子
[RenderWith(typeof(_ActivityIndicatorRenderer))]
public class ActivityIndicator : View, IElementConfiguration<ActivityIndicator>
{
//這就是值類型綁定的實現(xiàn)
public static readonly BindableProperty IsRunningProperty = BindableProperty.Create
("IsRunning", typeof(bool), typeof(ActivityIndicator), default(bool));
public static readonly BindableProperty ColorProperty = BindableProperty.Create
("Color", typeof(Color), typeof(ActivityIndicator), Color.Default);
readonly Lazy<PlatformConfigurationRegistry<ActivityIndicator>> _platformConfigurationRegistry;
public ActivityIndicator()
{
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<ActivityIndicator>>(() => new PlatformConfigurationRegistry<ActivityIndicator>(this));
}
public Color Color
{
get { return (Color)GetValue(ColorProperty); }
set { SetValue(ColorProperty, value); }
}
//與之對對應(yīng)的屬性
public bool IsRunning
{
get { return (bool)GetValue(IsRunningProperty); }
set { SetValue(IsRunningProperty, value); }
}
public IPlatformElementConfiguration<T, ActivityIndicator> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
}
Ps:這個官方例子是有問題的如输。
下面講一下如何綁定事件,其實 Xamarin Forms 綁定事件用的是 Command央勒,方法也不難不见。
public class MyEntry:Entry
{
public ICommand MyCommand
{
get => (ICommand )GetValue(MyCommandProperty);
set => SetValue(MyCommandProperty, value);
}
/// <summary>
/// MyCommandProperty的Mvvm實現(xiàn)
/// </summary>
public static readonly BindableProperty MyCommandProperty = Create
(
nameof(回調(diào)方法),
typeof(ICommand),
typeof(MyEntry)
); //注意這里變量名的命名規(guī)則是MyCommand + Property,前者隨便崔步,后者固定語法
private void 回調(diào)方法()
{
MyCommand?.Execute(null);
}
}
//這樣這個MyEntry的MyCommand就可以被Mvvm綁定了稳吮。
用法:
View
<MyEntry MyCommand={ Binding ThisCommand ></MyEntry>
ViewModel
public class Model:某個mvvm框架的BasePage
{
public Command ThisCommand
{
get
{
retrun new Command(()=>
{
//做點什么
});
}
}
}