以xamarin形式在.xmal和.cs之间进行数据访问

时间:2017-04-22 05:11:25

标签: c# xamarin binding xamarin.forms

我在.xmal文件中选了一个标签。

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="ListDemo.TableView">

<StackLayout>
    <Label Text="Above TableView"></Label>
    <TableView>
        <TableView.Root>
            <TableSection Title="Test">
                <EntryCell Label="EntryCell"></EntryCell>
                <TextCell Text="Test" Detail="Text Detail"></TextCell>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Horizontal" >
                            <BoxView Color="Red"></BoxView>
                            <StackLayout>
                                <Label Text="{Binding Receivename}"></Label>
                                <Label Text="News URL 1"></Label>
                            </StackLayout>
                            <BoxView x:Name="boxView" Color="Blue" ></BoxView>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </TableSection>
        </TableView.Root>
    </TableView>
</StackLayout>

我想从.cs文件中设置标签数据。

namespace ListDemo
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TableView : ContentPage
    {
        public TableView()
        {
            InitializeComponent();

           public string Receivename = "Hello";
        }
    }
}

请告诉我,如何设置Label的动态数据。在.cs文件中写什么。

提前致谢。

1 个答案:

答案 0 :(得分:1)

首先,您只能绑定到属性。所以你需要:

public string Recievename { get; set; }

其次,在构造函数中设置此数据时,它应该在实际类的范围内。

但是,您可以在构造函数中设置属性的值。只是不在那里定义。

按请求更新:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TableView : ContentPage
{
    public string Receivename { get; set; }

    public TableView()
    {
        InitializeComponent();
        BindingContext = this; //Need to set data context as well, if not defined in XAML
        Receivename = "Hello";
    }
}

我还建议你更多地了解绑定,属性通知等。关于xamarin的博客应该给你一个提示:https://blog.xamarin.com/introduction-to-data-binding/