如何在代码隐藏的 listView 中使用 x:Name 项目? [英] How to use x:Name of items in listView at codebehind?
本文介绍了如何在代码隐藏的 listView 中使用 x:Name 项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以在 xamarin.forms 的代码后面使用列表视图中堆栈布局的 x:Name 吗?
Is there any way to use x:Name of the stacklayout in listview at code behind in xamarin.forms?
<ListView HasUnevenRows="true" HeightRequist="{Binding ListHeight}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<StackLayout x:Name="btnStack/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
如何在代码隐藏中使用 btnStack
?
How to use btnStack
at codebehind?
推荐答案
为了能够通过名称和任何你喜欢的方式访问模板化元素,创建一个自定义视图,将你作为一个单元.在单元格的代码隐藏中,您将能够按名称访问所有内容.您的初始父列表现在将如下所示:
To be able to access templated elements by name and by whatever way you like, create a custom view that will serve You as a cell. And in the cell's code-behind you will be able to access everything by name. Your initial parent list will now look like:
<ListView HasUnevenRows="true" HeightRequest="{Binding ListHeight}">
<ListView.ItemTemplate>
<DataTemplate>
<user:MyViewCell/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
您全新的单元格将如下所示:
Your brand new cell will look like:
XAML:
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourNameSpace.MyViewCell">
<StackLayout x:Name="btnStack" Spacing="0">
<Label x:Name="txtEvenMore"/>
</StackLayout>
</ViewCell>
代码:
namespace YourNameSpace
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyViewCell
{
public MyViewCell()
{
InitializeComponent();
//you can init your cells here
InitCell(); //this is just for demo
}
public void InitCell()
{
//i can access my stack:
btnStack.BackgroundColor = Color.Red;
//and even more
txtEvenMore.Text = "By name? Yes! :)";
}
//Now not for demo but in the real world:
//We can set content according to your data from ItemsSource
//This will act when you set your ListView ItemsSource to something valid
protected override void OnBindingContextChanged()
{
SetupCell();
base.OnBindingContextChanged();
}
public void SetupCell()
{
//use data from ItemsSource
var item = BindingContext as YourItemClass;
if (item == null) return;
txtEvenMore.Text = item.SomeTextProperty;
//etc.. :)
}
}
}
祝你好运!:)
这篇关于如何在代码隐藏的 listView 中使用 x:Name 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文