对这个简单的绑定有问题。
尝试将字符串名称“carNames”的列表绑定到选择器,但不起作用。
当我将Picker.ItemSource设置为我的List“CarNames”时,我得到了显示的项目,但是当我在XAML中绑定时,它不起作用。
我试着把它变成一个ObservableCollection,但这对我也不起作用。
代码隐藏
using People.ViewModel;
namespace People.View;
public partial class CarView : ContentPage
{
List<Cars> cars;
CarSet carSet;
public List<string> carNames { get; set; } = new();
public CarView()
{
carSet = new CarSet(carNames);
InitializeComponent();
}
public void OnNewButtonCarClicked(object sender, EventArgs args)
{
CarMessage.Text = "";
App.CarRepo.AddNewCar(newModel.Text);
CarMessage.Text = App.CarRepo.CarMessage;
}
public void OnGetButtonCarClicked(object sender, EventArgs args)
{
CarMessage.Text = "";
cars = App.CarRepo.GetAllCars();
carsList.ItemsSource = cars;
}
}
字符串
XAML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="People.View.CarView"
Title="CarView">
<Grid RowDefinitions="80,80,80,80,80,*"
ColumnDefinitions="1000,*,*,*"
BackgroundColor="Black">
<Entry x:Name="newModel"
Placeholder="Enter Vehicle"
Grid.Column="1"
Grid.ColumnSpan="2"/>
<Button Text="Add Car"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="2"
Clicked="OnNewButtonCarClicked" />
<CollectionView x:Name="CarList"></CollectionView>
<Label x:Name="CarMessage"
Grid.Row="3"
Grid.Column="1"/>
<Button Text="Get All Cars"
Grid.Row="4"
Grid.Column ="1"
Grid.ColumnSpan="2"
Clicked="OnGetButtonCarClicked" />
<Picker x:Name="Picker"
Title="Select a Car"
ItemsSource="{Binding CarNames}"
ItemDisplayBinding="{Binding Cars}"
Grid.Column="0"/>
<CollectionView x:Name="carsList"
Grid.Row="5"
Grid.Column ="1"
Grid.ColumnSpan="2"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding CarId}"
Grid.Column="0"
FontSize="Medium"/>
<Label Grid.Column="2"
Text="{Binding Car}"
FontSize="Medium"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>```
型
1条答案
按热度按时间zkure5ic1#
我在这段代码中发现了几个问题。请按照以下步骤操作。
1.首先需要设置绑定上下文。在构造函数中添加以下代码
String = this;
1.在Xaml Picker中,“ItemsSource”和“ItemDisplayBinding”绑定值不正确。像下面这样更改该部分。
字符串
ItemsSource="{BindingcarNames}”
ItemDisplayBinding="{Binding汽车}”