Xamarin Forms - Get custom control runtime (with v

2020-05-10 05:21发布

问题:

I have a Xamarin forms application. It has a page. That page has a listview. The listviews is bind to a sourcelist. What I want is to decide what custom control to use based on a specific property that each item in the list has. How can I achieve this?

It is also required that the custom control binds to values from the list.

I tried the following:

                <ContentView Content="{Binding IsPriority, Converter={StaticResource RoadIndicatorBackgroundValueConverter}}" ControlText="{Binding TowingOrder.Location.RoadIndicator}"></ContentView>

That won't work because I can't bind with the ControlText of the specific custom control.

The image above shows the problem. The A1, A50 and the blue icons are all custom controls, those aren't images. There are some more of these custom controls. I can't just make 10 datatemplates right and copy paste everything? That would be so much duplicate code. Can't I just use a base object in a datatemplate, and bind a property with a converter and use a switch/case to decide which custom control to return?

回答1:

It is not a good design to binding the content of whole layout in runtime.

From the screen shot , it seems that each cell are similar .So you could create a base Custom Control and define all controls in advance and binding the propertyIsVisible in code behind . Then set its value to control which element should been displayed .

If there are do many dig differences between the cells , use DataTemplateSelector is better .