xamarin - Binding string with Button
问题描述
I am trying to bind a string
to a Button
in pure C# (no XAML), but apparently I am doing it wrong, as the result of my code is that the button disappears.
I am defining my property as follows:
public string selectionString { get; set; }
And this is how I am binding the string to the button:
selectionString = "Hello";
selectionButton = new Button
{
TextColor = Color.Black
};
selectionButton.SetBinding(Button.TextProperty, "selectionString");
Children.Add(selectionButton);
I have tried to use BindingMode.TwoWay
, but it doesn't work.
Of course, setting the text and removing the binding makes the button appear and work.
My need is just this: the button text should be the selectionString
, and if this changes by an external event, so the button's text should change accordingly.
Am I missing something in how the binding works?
解决方案
Bindings work against public properties on the view's binding context, and respond to INotifyPropertyChanged events firing. Hopefully this demonstrates for you.
public class MyViewModel : INotifyPropertyChanged
{
// Fire RaisePropertyChanged in the setter, I use Fody to weave this in
public string SelectionString {get;set;}
}
public class MyView : Page
{
protected override void OnBindingContextChanged()
{
if (BindingContext is MyViewModel)
{
this.SetBinding(Button.TextProperty, "SelectionString");
}
}
}
推荐阅读
- ios - 如何使用导航控制器关闭两个视图控制器?
- python - 在 selenium python 绑定中修改语言选项时遇到问题
- function - 在 If 语句中传递参数
- php - 减少大型数据库调用 php 的内存使用量
- arrays - 同时在维度 attr-spec 和 entity-decl 中声明 array-spec
- python - 如何根据某些条件自动设置 django 模型属性?
- .net - 如何使用 .NET Oracle 连接执行第二个命令?
- arrays - 希望在数组上重复一个函数 N 次
- node.js - 如何在此代码中集成和发送图像裁剪(angular2-img-cropper)?
- .net - Device Hub 与打印机队列的通信