如何在代码隐藏处使用x:listView中的项目名称? [英] How to use x:Name of items in listView at codebehind?
本文介绍了如何在代码隐藏处使用x:listView中的项目名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在xamarin.forms后面的代码中,有什么方法可以在列表视图中使用x:stacklayout的名称吗?
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.. :)
}
}
}
祝你好运! :)
这篇关于如何在代码隐藏处使用x:listView中的项目名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文