[英]Xamarin.Forms accessing controls written in markup from Code
Im trying to add some items to a Listview which i added using Xamarin.Forms markup in an xaml file. 我试图将一些项添加到Listview,我在xaml文件中使用Xamarin.Forms标记添加。 The button can be accessed by hooking with the click event.But since the listview is empty i need the event like ondraw
like in winforms, so that i can hook to it when it is drawn. 可以通过单击事件挂钩来访问该按钮。但由于列表视图为空,我需要像winforms中的ondraw
这样的事件,以便在绘制时可以挂钩。
In the XAML file I have : 在XAML文件中,我有:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ButtonXaml.ButtonXamlPage">
<StackLayout>
<Button Text="Tap for click count!"
BorderWidth="10"
TextColor="Red"
HorizontalOptions="Center"
Clicked="OnButtonClicked" />
<ListView
HorizontalOptions="Center"
/>
</StackLayout>
</ContentPage>
In the .cs file i have 在我的.cs文件中
using System;
using Xamarin.Forms;
namespace ButtonXaml
{
public partial class ButtonXamlPage
{
int count = 0;
public ButtonXamlPage()
{
InitializeComponent();
}
public void OnButtonClicked(object sender, EventArgs args)
{
((Button)sender).Text = "You clicked me";
}
}
}
So should i hook to events in Listview or can i do something like Resource.getElementbyID
like we do in android 所以我应该挂钩Listview中的事件,还是像我们在android中那样做一些类似Resource.getElementbyID
事情
To access a Forms control in the code-behind, you need to assign it a name, using the x:Name
attribute 要在代码隐藏中访问Forms控件,您需要使用x:Name
属性为其指定x:Name
in XAML: 在XAML中:
<ListView HorizontalOptions="Center" x:Name="MyList" />
in code: 在代码中:
MyList.ItemsSource = myData;
There is a bug in Xamarin where VS doesn't see the defined x:Name http://forums.xamarin.com/discussion/25409/problem-with-xaml-x-name-and-access-from-code-behind Xamarin中有一个错误,VS没有看到定义的x:名称http://forums.xamarin.com/discussion/25409/problem-with-xaml-x-name-and-access-from-code-behind
Say you've defined an image in XAML: 假设您已在XAML中定义了一个图像:
<Image x:Name="myImageXName" />
Then this should work in code behind: 那么这应该在代码后面工作:
this.FindByName<Image>("myImageXName");
In my case the problem was lack of line XamlCompilation(XamlCompilationOptions.Compile)]
in .xaml.cs file. 在我的例子中,问题是.xaml.cs文件中没有行XamlCompilation(XamlCompilationOptions.Compile)]
。
Example: 例:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.