Hi all.
As you know in xaml for each content page you can specify it's resource dictionary and use them like this
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyClass" xmlns:local="clr-namespace:MyProject.Forms;assembly=MyProject"> <ContentPage.Resources> <ResourceDictionary> <local:InverseBoolConverter x:Key="inverse" /> <local:BoolToOpacityConverter x:Key="opacity" /> <local:InverseBoolToOpacityConverter x:Key="inverseOpacity" /> </ResourceDictionary> </ContentPage.Resources> <ContentPage.Content> <StackLayout Padding="0,20,0,5" IsVisible="{Binding IsNetworkAvailable, Converter={StaticResource inverse}}"> ...... </StackLayout> </ContentPage.Content> </ContentPage>
I'm also used to create ListView cell templates in separate xaml file to reuse them in different xaml pages. However I didn't find a way to use ResourceDictionary in my custom ViewCell xaml. I tried something like this
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyListCell" xmlns:local="clr-namespace:MyProject;assembly=MyProject"> <ViewCell.Resources> <ResourceDictionary> <local:BoolToOpacityConverter x:Key="opacity" /> <local:InverseBoolToOpacityConverter x:Key="inverseOpacity" /> </ResourceDictionary> </ViewCell.Resources> </ViewCell>
However I get runtime exception that ViewCell doesn't have Resources property. Anyone knows how to achieve this? My pain purpose is being able to use converters in custom ViewCell xaml, and perhaps there is other way of doing that. Please don't comment that you can use custom property on BindingContext and place the converted data into that property instead of using converter, I know that. But I don't want to create custom property when the best practice in MVVM is creating converter. Any ideas?
Posts
I'm also interested if someone has an answer
I've figured this out!
Here is a sample code.
What I did I've tried to find the base class for ContentPage which declares Resources dictionary property, and I've found that! It was VisualElement. If you look into ViewCell documentation it inherits from Cell class, which inherits from Element class not VisualElement. Perhaps the the ViewCell is not VisualElement because of performance reasons, I don't know. Anyhow, it doesn't take a genius to understand that for the solution of this problem we need a subclass of VisualElement somewhere inside ViewCell. For instance StackLayout can work for this purpose, I've tried and IT WORKED
This is a neat trick! Nice work.