有人知道如何将对象绑定到不同的项目吗?
例如我有2个项目。一个是我的 maui 应用程序,其中包含 Mainpage.xaml,另一个是我想重用的 dll。
假设 dll 显示一个带有一些自定义的简单列表。
在我的 Maui 应用程序中,我想调用 dll(xaml 视图)并将其绑定到我创建的列表以便显示它。
我在这里举了一个例子:
https://github.com/VincentS90/TestBindingProperty.git
listItems 被实例化并在其他地方填充。 我怎样才能正确地“转移”这个ListItems以在dll中使用?
目前,执行时什么也没有出现。不知道是语法问题还是概念问题。
谢谢
查看您的存储库,您正在一个项目中创建自定义视图,并且希望在保存对其引用的第二个项目中使用该视图。首先,让我们看一个将使用自定义视图的示例类:
namespace net_maui_list_consumer
{
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new MainPageModel();
InitializeComponent();
}
}
class MainPageModel
{
public ObservableCollection<Object> Fruits { get; } = new ObservableCollection<object>
{
new Fruit{ Name = "Apple", Color = Colors.Red },
new Fruit{ Name = "Orange", Color = Colors.Orange },
new Fruit{ Name = "Banana", Color = Color.FromRgb(255, 204, 0) },
};
}
class Fruit
{
public string Name { get; set; }
public Color Color { get; set; }
}
}
我们希望使用外部
ListView
组件以某种自定义方式显示它:
所以在一个项目中我们称之为
IVSoftware.Maui.Demo.Components
,自定义视图可能会这样定义:
CS
namespace IVSoftware.Maui.Demo.Components;
public partial class DisplayList : ListView
{
public DisplayList() => InitializeComponent();
}
Xaml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="IVSoftware.Maui.Demo.Components.DisplayList">
<ListView.ItemTemplate ItemsSource="{Binding ListFromExternalDLL}">
<DataTemplate>
<ViewCell>
<!-- Define the layout for each item in the list -->
<StackLayout>
<Frame
CornerRadius="20"
BackgroundColor="{Binding Color}">
<Label
Text="{Binding Name}"
TextColor="White"
HeightRequest="50"
FontSize="Medium"/>
</Frame>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
使用外部项目中的
DisplayList
的“技巧”是限定 xmlns
中的程序集,如下所示:
主项目中的Xaml
<?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"
xmlns:ivs="clr-namespace:IVSoftware.Maui.Demo.Components;assembly=IVSoftware.Maui.Demo.Components"
x:Class="net_maui_list_consumer.MainPage">
<Grid>
<ivs:DisplayList ItemsSource="{Binding Fruits}"/>
</Grid>
</ContentPage>