在 xaml 中绑定到 C# 代码的 Xamarin ListView
Xamarin ListView with Binding in xaml to C# code
如何将 xaml
文件中带有 ItemTemplate
和 Binding
的以下 ListView 转换为等效的 C# 代码:
<ListView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
ItemsSource="{Binding A}" ItemSelected="OnClick">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding b}" Detail="{Binding c}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
尝试这样的事情:
ListView lv = new ListView();
lv.HorizontalOptions = LayoutOptions.FillAndExpand;
lv.VerticalOptions = LayoutOptions.FillAndExpand;
lv.SetBinding(ListView.ItemsSourceProperty, new Binding("A"));
lv.ItemSelected += (sender, args) =>
{
onclick(sender, args);
}; //Remember to remove this event handler on dispoing of the page;
DataTemplate dt = new DataTemplate(typeof(TextCell));
dt.SetBinding(TextCell.TextProperty, new Binding("b"));
dt.SetBinding(TextCell.DetailProperty, new Binding("c"));
lv.ItemTemplate = dt;
对于更复杂的Datatemplates
做:
DataTemplate dt = new DataTemplate(() =>
{
var button = new Button();
button.SetBinding(Button.TextProperty, new Binding("Name"));
return new ViewCell { View = button };
});
如何将 xaml
文件中带有 ItemTemplate
和 Binding
的以下 ListView 转换为等效的 C# 代码:
<ListView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
ItemsSource="{Binding A}" ItemSelected="OnClick">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding b}" Detail="{Binding c}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
尝试这样的事情:
ListView lv = new ListView();
lv.HorizontalOptions = LayoutOptions.FillAndExpand;
lv.VerticalOptions = LayoutOptions.FillAndExpand;
lv.SetBinding(ListView.ItemsSourceProperty, new Binding("A"));
lv.ItemSelected += (sender, args) =>
{
onclick(sender, args);
}; //Remember to remove this event handler on dispoing of the page;
DataTemplate dt = new DataTemplate(typeof(TextCell));
dt.SetBinding(TextCell.TextProperty, new Binding("b"));
dt.SetBinding(TextCell.DetailProperty, new Binding("c"));
lv.ItemTemplate = dt;
对于更复杂的Datatemplates
做:
DataTemplate dt = new DataTemplate(() =>
{
var button = new Button();
button.SetBinding(Button.TextProperty, new Binding("Name"));
return new ViewCell { View = button };
});