c# - 如何在 xamarin 中更改标签文本

标签 c# xaml xamarin xamarin.forms

我对 Xamarin 表单比较陌生。我发现我无法从后面的代码更改标签文本。通常我会做 myLabel.text = variable。这在 Xamarin 中有效吗?如果是这样,为什么这段代码不更改文本?

Label_ControlSW.Text = controlSW_Out;
            Label_BLESW.Text = bleSW_Out;
            Label_Mode.Text = mode_Out;

Xaml 文件

<Label x:Name="Label_ControlSW" Grid.Row="1" Grid.Column="1" HorizontalOptions="Center"  VerticalOptions="Center" FontSize="17" TextColor="White"/>
                <Label x:Name="Label_BLESW" Grid.Row="2" Grid.Column="1" HorizontalOptions="Center"  VerticalOptions="Center" FontSize="17" TextColor="#525252"/>
                <Label x:Name="Label_Mode"  Grid.Row="4" Grid.Column="1" HorizontalOptions="Center"  VerticalOptions="Center" FontSize="17" TextColor="White"/>

最佳答案

Does this work in Xamarin?

是的,确实如此。

If it does why does this code not change the text?

因为 Label 组件没有绑定(bind)到变量,它只是在您执行 Label_ControlSW.Text = controlSW_Out; 时获取其值,仅此而已。

要使其正常工作,您基本上有两种选择:

<强>1。在每次更改时将值设置为标签;

这里没有魔法。只需设置值或变量,如 Ali Heikal's answer建议,但您必须每次都手动执行此操作。

<强>2。将页面( View )绑定(bind)到一个 Observable 对象(模型),然后 View 将监听模型上的每个更改并对此使用react(例如,更改它自己的 Text 值) .

我猜你打算做的是第二个。因此,您可以在页面的代码隐藏中创建一个公共(public)字符串属性,并将页面实例绑定(bind)到自身。像这样:

XAML

<Label Text="{Binding MyStringProperty}"
       .../>

代码隐藏

public partial class MyTestPage : ContentPage
{
    private string myStringProperty;
    public string MyStringProperty
    {
        get { return myStringProperty; }
        set 
        {
            myStringProperty = value;
            OnPropertyChanged(nameof(MyStringProperty)); // Notify that there was a change on this property
        }
    }
    
    public MyTestPage()
    {
        InitializeComponents();
        BindingContext = this;

        MyStringProperty = "New label text"; // It will be shown at your label
    }
}

你应该看看official docs about data bindings and MVVM pattern on XF如果您开始使用 Xamarin.Forms,我强烈建议您遵循 official getting started guide清晰而深入地阐述每个主题,足以让您了解所需的一切。

希望对你有帮助。

关于c# - 如何在 xamarin 中更改标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366271/

相关文章:

c# - 如何强行关闭 TcpListener

c# - 如何使用系统命名空间创建扩展方法

c# - c# 枚举是否有基础对象?

c# - 在特定位置显示 UI 元素上方的浮出控件

c# - XAML 中的自定义类给我带来了 Unresolved 标记错误

c# - 画图 : Canvas is not drawing bitmap

c# - 在 C# 中,为什么 String 是一种行为类似于值类型的引用类型?

windows-phone-7 - 如何在全景中使用水平 WrapPanel (sketchflow)

xamarin - Android SDK 构建工具是什么?

xamarin - 我需要阻止 XamarinForms 上日期选择器中的粘贴功能