Wil*_*ohn 1 c# xamarin xamarin.forms
尝试通过字符串将文本绑定到我的xaml,并使用propertychanged函数根据int的值更改文本.这是我的代码:
XAML:
<Label Text = "{Binding Forename}" />
Run Code Online (Sandbox Code Playgroud)
码:
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged (string propertyName)
{
var changed = PropertyChanged;
if (changed != null) {
PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
}
}
string info;
int myInt = 0;
public string Forename {
get {
return info;
}
set {
if (myInt == 0) {
info = value;
OnPropertyChanged ("TextOne");
}
else if (myInt == 1)
{
OnPropertyChanged ("TextTwo");
}
else
{
OnPropertyChanged ("TextThree");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我现在没有文字.
那不是多么OnPropertyChanged()有效.您不应传递要作为参数显示的新文本,而应将新文本分配给info字段,并将属性的名称作为参数.
什么OnPropertyChanged(name)是告诉XAML属性name已更改,XAML将在该属性上获取该属性,并相应地更新显示的值.
public string Forename {
get {
return info;
}
set {
if (myInt == 0) {
info = value;
OnPropertyChanged ("Forename");
}
else if (myInt == 1)
{
info = "TextTwo";
OnPropertyChanged ("Forename");
}
else
{
info = "TextThree";
OnPropertyChanged ("Forename");
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
当你对应该投入的内容有一些疑问时protected virtual void OnPropertyChanged(string propertyName),这个功能就好了.当它被调用时,它将使用PropertyChangedEventHandler PropertyChangedto让事件的所有子程序员知道属性propertyName已经改变.XAML {Binding Forename}充当它的订阅者/侦听者PropertyChanged,并且一旦被告知它绑定的属性("Forename")已经改变就会更新它的文本.拨打电话时会发生什么OnPropertyChanged("Forename").
编辑2 似乎您可能忘记分配您的DataContext在XAML的代码隐藏中(将命名为mainwindow.xaml.cs)
InitializeComponent();
ViewModel vm = new ViewModel();
DataContext = vm;
vm.Forename = "TestString"
Run Code Online (Sandbox Code Playgroud)
并将Forename-code的东西移到一个单独的类中,命名为ViewModel.像这样:
public class ViewModel{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged (string propertyName)
{
var changed = PropertyChanged;
if (changed != null) {
PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
}
}
string info;
int myInt = 0;
public string Forename {
get {
return info;
}
set {
if (myInt == 0) {
info = value;
OnPropertyChanged ("Forename");
}
else if (myInt == 1)
{
info = "TextTwo";
OnPropertyChanged ("Forename");
}
else
{
info = "TextThree";
OnPropertyChanged ("Forename");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |