Reputation: 332
I created a CollectionView inside which has a custom View.
I want to specify the property of the customview dynamically so I add a Binding Value to the customView but obviously it need a Property in the Binding Data.
But I want to specify it in the cs file.
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<local:MyView WidthRequest="{Binding Width}"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
obviously I need add a Width property in the Items.But I do not want it. Is there anyway to do it?
Upvotes: 0
Views: 487
Reputation: 18861
Different from Button and Image . ContentView will not have a default size if you don't set the child elements .
So if you want to set the size in runtime , use data binding is the best way . If you don't want to define the property in model and set it multi times , you can set the binding path of the ContentView . In this way you should make sure that each row has the same height .
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:XXX"
mc:Ignorable="d"
x:Name="contentPage" // set the name
x:Class="XXX.MainPage">
<local:MyView HeightRequest="{Binding Source={x:Reference contentPage},Path=BindingContext.Height}" />
public double Height {get; private set;}
Upvotes: 1
Reputation: 332
I have a not so better solution.
I created a style which specify the HeightReqeust
and WidthRequest
of the customView.
and I specify the value in the cs file.
till now I have not found a better solution.
Upvotes: 0
Reputation: 8124
Try to use <Grid>
with one column specifying it's width as Auto
instead of binding dynamic Width
:
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<local:MyView Grid.Column="0"/>
<Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Upvotes: 0