![](/img/trans.png)
[英].NET MAUI - How to bind on a property of an ObservableCollection Item
[英].net Maui ViewList Binding with an ObservableCollection
我有一個 ObservableCollection: 標簽
為此屬性:標簽
它們應該是我的列表視圖的 ItemsSource:tagList
到目前為止,我從另一種方法中得到了一個列表,並一直將它們迭代到標簽中,但現在這需要太長時間。
但是現在我找到了一種更簡單的方法來填充列表,而無需從一個到另一個迭代,但問題是。 但它沒有在 Listview 中顯示標簽,所以我嘗試按照 xml 代碼綁定它,但它似乎不起作用。
這是 XML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TagEditor.TagPage"
Title="TagPage">
<VerticalStackLayout
Spacing="5"
HorizontalOptions="Center">
<RefreshView
x:Name="RefreshScroll">
<ScrollView
HeightRequest="500"
WidthRequest="500"
VerticalOptions="StartAndExpand"
VerticalScrollBarVisibility="Always"
>
<VerticalStackLayout>
<ListView
x:Name="tagList"
ItemsSource="{Binding Tags}"
BackgroundColor="LightGray"
>
</ListView>
</VerticalStackLayout>
</ScrollView>
</RefreshView>
</VerticalStackLayout>
</ContentPage>
這是 c# 代碼
private ObservableCollection<Tag> tags = new();
public ObservableCollection<Tag> Tags { get { return tags; } set { tags = value; } }
public TagPage(TagFinder tagFinder)
{
MessagingCenter.Subscribe<MainPage>(this, "DISCONNECT", (sender) =>
{
MainThread.BeginInvokeOnMainThread(() =>
{
Application.Current?.CloseWindow(this.Window);
});
});
InitializeComponent();
tagList.ItemsSource = Tags;
try
{
UpdateSearchresults();
}
catch (FileNotFoundException e)
{
DisplayAlert("Error", e.Message, "Ok");
}
}
我需要做什么才能將標簽用作 ItemsSource?
根據你的代碼,我做了一個測試,它對我有用。
您可以添加Cell
label 以顯示ListView
的每個項目。
請參考以下代碼:
<ListView x:Name="tagList"
ItemsSource="{Binding Tags}"
BackgroundColor="LightGray">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}"
Detail="{Binding MyProperty}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
注意:綁定到TextCell
的Name
和MyProperty
都是我自己定義的。
這是使用 Xml Linq 的解決方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetDefaultNamespace();
XNamespace nsX = doc.Root.GetNamespaceOfPrefix("x");
XElement listView = doc.Descendants(ns + "ListView").FirstOrDefault();
string name = (string)listView.Attribute(nsX + "Name");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.