我有一个从StackLayout派生的自定义控件,它包含两个标签。每个标签的Text属性都绑定到代码隐藏中的一个属性
public string Label1Text
{
get { return _label1Text; }
set
{
_label1Text = value;
OnPropertyChanged(nameof(Label1Text));
}
}标签的文本内容由控件使用者设置的代码幕后中的单独BindableProperty的内容确定,因此标签绑定到的属性在自定义控件之外不应真正可见。
如果我在代码中将属性设置为private,则控件的Xaml中的绑定将不起作用。但是,当设置为public时,它们在Intellisense中可见,这是错误的,因为它们仅供内部使用。
我可以设置属性
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]但是这是正确的处理方法吗,因为它只隐藏了属性,而不是实际上阻止它们被控件的使用者设置?
发布于 2020-10-22 13:12:04
您可以直接在Label.Text和viewmodel的属性之间创建绑定。
并定义仅供自定义控件内部内部使用的私有属性。
ViewModel
public class Model
{
public string TextA { get; set; }
public string TextB { get; set; }
}页面
//code behind
public Page2()
{
InitializeComponent();
Model model = new Model
{
TextA = "ABCD",
TextB = "1234"
};
this.BindingContext = model;
}
//xaml
<ContentPage.Content>
<local:MyStack />
</ContentPage.Content>自定义控件
//code behind
public partial class MyStack : ContentView
{
private string A { get; set; } //internal use
private string B { get; set; } //internal use
public MyStack()
{
InitializeComponent();
this.BindingContextChanged += MyStack_BindingContextChanged;
}
private void MyStack_BindingContextChanged(object sender, EventArgs e)
{
var model = this.BindingContext as Model;
A = model.TextA;
B = model.TextB;
}
}
//xaml
<ContentView.Content>
<StackLayout>
<Label Text="{Binding A}" TextColor="Red"/>
<Label Text="{Binding B}" TextColor="Green"/>
</StackLayout>
</ContentView.Content>https://stackoverflow.com/questions/64467273
复制相似问题