How to reference converter in a ResourceDictionary file - forms

I'm trying to create a resource dictionary file and reference a Value Converter. How can this be done?
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:CS.Runtime.Crew.Converters"
x:Class="CS.Runtime.Crew.Resources.CrewResourceDictionary" >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<!--<converters:DateTimeToNullableDateTimeConverter x:Key="DateTimeToNullableDateTimeConverter" />-->
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="workGroupAttributesTemplate">
<Grid>
<controls:ExtendedDatePicker NullableDate="{Binding Attributes[DueDate], Converter={StaticResource DateTimeToNullableDateTimeConverter}}" Grid.Column="1" Grid.Row="4" />
</Grid>
</DataTemplate>
</ResourceDictionary>

First you add the class namespace
We assume class is Checker and checker is the namespace
Header
xmlns:checker="clr-namespace:Something.Checker;assembly=Something
Body
<checker:MySpecialValueConverter x:Key="MySpecialValue"/>
You can read more here
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters#the-ivalueconverter-interface

Related

Correct AbsoluteLayout positioning/overlay

The main goal of the task to create AutoSuggest control.
In my case AutoSuggest control is custom control inherited from Grid
<Grid xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
...
xmlns:handlers ="clr-namespace:CrowdExchangeV2.Controls.Handlers"
WidthRequest="150">
<Grid.RowDefinitions>
<RowDefinition Height="35"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Frame Grid.Row="0"
...>
<handlers:BorderlessEntry Placeholder="{Binding Source={x:Reference this}, Path=Placeholder}"
WidthRequest="150"
.../>
</Frame>
<AbsoluteLayout
WidthRequest="150"
MaximumHeightRequest="100"
Grid.Row="1"
x:Name="resAl">
<ScrollView
MaximumHeightRequest="100"
MaximumWidthRequest="160"
x:Name="resSV">
<CollectionView x:Name="list">
<CollectionView.ItemTemplate>
<DataTemplate>
<HorizontalStackLayout VerticalOptions="Center"
HorizontalOptions="Start">
<Label Text="{Binding Key}" Padding="0,0,4,0"/>
<Label Text="{Binding Value}"/>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ScrollView>
</AbsoluteLayout>
</Grid>
So, control looking for suggestions in Dictionary while user typing text in Entry. The thing is - when CollectionView updates suggestions it pushes all the other elements on ContentPage down... but suppose to overlay them. All right lets wrap Suggester in AbsoluteLayout on contentPage and setBounds to a desirable position. (PS: Suggester name is suggester 0_o)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
...
Title=" ">
<AbsoluteLayout x:Name="mainAbs">
<AbsoluteLayout Margin="0,0,0,0"
x:Name="suggestAl">
<suggester:Suggester Placeholder="USD"
SearchDictionary="{Binding SearchCurrency}"
MaximumHeightRequest="150"
MaximumWidthRequest="150"/>
</AbsoluteLayout>
<Grid Padding="10" AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="All">
<ScrollView>
<VerticalStackLayout>
...
<Frame HorizontalOptions="Fill">
<VerticalStackLayout>
...
<VerticalStackLayout HeightRequest="80"
x:Name="currVSL">
<Label Text="Currency out:"
VerticalOptions="Start"
HorizontalOptions="Start"
FontSize="Header"
x:Name="curLbl"/>
**SUggester should be here**
</VerticalStackLayout>
</VerticalStackLayout>
</Frame>
</VerticalStackLayout>
</ScrollView>
</Grid>
</AbsoluteLayout>
</ContentPage>
The first idea is - to grab x:Name="currVSL" bounds, adjust it for size of Label, and place x:Name="suggestAl" there, but i cant get absolute position of x:Name="currVSL" only relative and in absolute terms it's wrong
I don't want to hardcode position in static numbers, because the position highly depends on a particular device.
So the question is how to achieve a desirable result - Place x:Name="currVSL" under the x:Name="curLbl" label.
OR
Might be there is a more elegant solution to show suggestion results without pushing all the other elements down?(Read:overlay other elements on UI)
Image to visualise UI

How do I get the Maui ListView ContextMenu to bind to my viewmodel command

I have the following XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="MyApp.Pages.Locations.LocationsList"
xmlns:mvvm="clr-namespace:MvvmHelpers;assembly=MvvmHelpers"
xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Command="{Binding AddCommand}" />
</ContentPage.ToolbarItems>
<ContentPage.Behaviors>
<toolkit:EventToCommandBehavior EventName="Appearing" Command="{Binding LoadCommand}" />
</ContentPage.Behaviors>
<ContentPage.Resources>
<ResourceDictionary>
<toolkit:SelectedItemEventArgsConverter x:Key="SelectedItemEventArgsConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ListView BackgroundColor="Transparent"
CachingStrategy="RecycleElement"
ItemsSource="{Binding Locations}"
SelectedItem="{Binding SelectedLocation, Mode=TwoWay}"
SeparatorVisibility="None"
HasUnevenRows="True">
<ListView.Behaviors>
<toolkit:EventToCommandBehavior
EventName="ItemSelected"
EventArgsConverter="{StaticResource SelectedItemEventArgsConverter}"
Command="{Binding SelectCommand}"/>
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Delete" IsDestructive="True"
Command="{Binding DeleteCommand}"
CommandParameter="{Binding .}" />
<MenuItem Text="Edit" Command="{Binding EditCommand}"
CommandParameter="{Binding .}" />
</ViewCell.ContextActions>
<Grid Padding="10">
<Frame>
<StackLayout Orientation="Horizontal">
<Image Source="map.png" WidthRequest="40" />
<StackLayout Orientation="Vertical" Padding="10,0,0,0">
<Label VerticalOptions="Center"
FontSize="Medium"
Text="{Binding Name}" />
<Label VerticalOptions="Center"
FontSize="Micro"
Text="This is where the address will go." />
</StackLayout>
</StackLayout>
</Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
My ViewModel uses the Maui Community Toolkit and has 4 AsyncCommands defined
LoadCommand
SaveCommand
DeleteCommand
EditCommand
The LoadCommand and SaveCommand work perfectly but the DeleteCommand and EditCommand do not fire. I assume it's something to do with the commands being on the viewmodel and NOT on the item source model. How do I get it to trigger the AsyncCommands on the viewmodel?
Thanks
For this, you can check document Define MenuItem behavior with MVVM.
The MenuItem class supports the Model-View-ViewModel (MVVM) pattern through BindableProperty objects and the ICommand interface. The following XAML shows MenuItem instances bound to commands defined on a viewmodel:
<?xml version="1.0" encoding="utf-8" ?>
<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:viewmodels="clr-namespace:MenuItemDemos.ViewModels"
mc:Ignorable="d"
x:Class="MenuItemDemos.MenuItemXamlMvvmPage"
x:Name="myContentpage"
Padding="10"
Title="MenuItem XAML MVVM Demo"
>
<ContentPage.BindingContext>
<viewmodels:ListPageViewModel />
</ContentPage.BindingContext>
<StackLayout>
<Label Text="Reveal the context menu by right-clicking (UWP), long-pressing (Android), or swiping (iOS) an item in the following list." />
<Label Text="{Binding Message}"
TextColor="Red"
HorizontalOptions="CenterAndExpand"
VerticalOptions="Start" />
<ListView ItemsSource="{Binding Items}"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Edit"
IconImageSource="icon.png"
Command="{Binding Source={x:Reference myContentpage}, Path=BindingContext.EditCommand}"
CommandParameter="{Binding .}"/>
<MenuItem Text="Delete"
Command="{Binding Source={x:Reference myContentpage}, Path=BindingContext.DeleteCommand}"
CommandParameter="{Binding .}"/>
</ViewCell.ContextActions>
<Label Text="{Binding .}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
The viewmodel(ListPageViewModel.cs) contains the commands referenced in the XAML:
public class ListPageViewModel : INotifyPropertyChanged
{
...
public ICommand EditCommand => new Command<string>((string item) =>
{
Message = $"Edit command was called on: {item}";
});
public ICommand DeleteCommand => new Command<string>((string item) =>
{
Message = $"Delete command was called on: {item}";
});
}

How to bind ResourceDictionary to ViewModelProperty

I have ViewModel for MainWindow with property UriResource. How can I bind this property to ResourceDictionary? I have tried this code:
<Window.Resources>
<ResourceDictionary Source="{Binding UriResource}">
</ResourceDictionary>
</Window.Resources>
but I get error: All objects added to an IDictionary must have a Key attribute or some other type of key associated with them.
This is how my app.settings look like:
<Application x:Class="PcgTools.App"
...
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="....." />
</ResourceDictionary.MergedDictionaries>
<local:EnumToBooleanConverter x:Key="EnumToBooleanConverter"/>
<BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
<res:Strings
x:Key="LocStrings"/>
</ResourceDictionary>
</Application.Resources>
</Application>
Probably you need to add x:Key="....."

TreeView HierarchicalDataTemplate with Navigation Properties EntityFramework

I have three linked Entities (Categories->Types->Classes) with one to many relationship.
Is it possible to bind only Categories entity and represent the rest using Navigation properties andHierarchicalDataTemplate ?
I imagine something like this :
<TreeView ItemsSource="{Binding Categories}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Categories}" >
<TextBlock Foreground="Red" Text="{Binding Types}" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Classes}">
<TextBlock Text="{Binding TypeName}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate >
<TextBlock Text="{Binding ClassName}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
I've done this recently, in a WPF project, I've updated the Types to match your names and Nav Properties.
You might want to consider changing Type/Class to something more specific since they're used as keywords in the c# language, but I think you get the idea
<!-- The Root Category Table -->
<HierarchicalDataTemplateDataType="{x:Type Entities1:Categories}" ItemsSource="{Binding Types}" >
<StackPanel Orientation="Horizontal">
<Image Name="img" Source="{Binding ., Converter={Converters:DataTypeImageConverter}}" />
<TextBlock Text="{Binding CategoryName}" FontWeight="Bold" />
</StackPanel>
</HierarchicalDataTemplate>
<!-- Your Type Table -->
<HierarchicalDataTemplate DataType="{x:Type Entities1:Type}" ItemsSource="{Binding Classes}" >
<StackPanel Orientation="Horizontal">
<Image Name="img" Source="{Binding ., Converter={Converters:DataTypeImageConverter}}" />
<TextBlock Text="{Binding TypeName}" />
</StackPanel>
</HierarchicalDataTemplate>
<!-- Your Class Table-->
<DataTemplate DataType="{x:Type Entities1:Class}">
<StackPanel Orientation="Horizontal">
<Image Name="img" Source="{Binding ., Converter={Converters:DataTypeImageConverter}}" />
<TextBlock Text="{Binding ClassName}" />
</StackPanel>
</DataTemplate>
What this will do is, it will match the datatype in the tree - If it matches Category, it will create the stackpanel, then start another branch, using the navigation collection Types.
For types, it will do the same basic thing - create the panel for that item, then another branch, for it's navigation collection Class.
If it's class, it will only create the panel, since it's a DataTemplate, not a HierarchicalDataTemplate

Own DataTemplateSelector MVVM

I'm using a MVVM-Pattern with a ModelView-First approach. This works fine, so far.
Now I have a UserControl (View) which should display various content depending on a Property located in my ViewModel.
First, I tried to solve the issue with DataTemplates and a DataTemplateSelector (See this tutorial) This was working very well. But I was not happy with the solution, because then I have a class (the overrided DataTemplateSelector) which is not connected to the ViewModel and can't be filled from the model.
So I tried to create a own TemplateSelector which uses a Property from the ViewModel. Unfortunately the DataTrigger is not triggering. The Binding from a CheckBox to the ViewModel is also working but not at the DataTrigger (even the designer can't find this path).
Ok, please have a look at the code:
<UserControl.Resources>
<!--Define Template which is displayed for Users-->
<DataTemplate x:Key="templateUser">
<Image
Name="logo"
Source="blanked out"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</DataTemplate>
<!--Define Template which is displayed for Administrators-->
<DataTemplate x:Key="templateAdmin">
<TextBlock Background="Yellow" Margin="3" Text="YEAH, I'm an Administrator" />
</DataTemplate>
<!--My own TemplateSelectpr-->
<DataTemplate x:Key="myTemplateSelector">
<ContentControl x:Name="DynamicContent" ContentTemplate="{StaticResource templateUser}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsAdministrator}" Value="true">
<Setter TargetName="DynamicContent" Property="ContentTemplate" Value="{StaticResource templateAdmin}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentPresenter ContentTemplate="{StaticResource myTemplateSelector}"/>
</Grid>
Of course, I can seperate the Task in two further contentcontrols, but I don't want to maintain those if same content is intersecting.
So can someone suggest anything?
Best regards, and thanks in advance!
The simpler, the better: use a single template, which includes all the controls you need to show. Then switch their visibility using a binding to your property:
<UserControl.Resources>
<DataTemplate x:Key="myTemplate">
<Grid>
<Grid Visibility="{Binding IsAdministrator, Converter={StaticResource BooleanToVisibilityConverter}}">
<!-- Content for admin -->
</Grid>
<Grid Visibility="{Binding IsAdministrator, Converter={StaticResource NotBooleanToVisibilityConverter}}">
<!-- Content for user -->
</Grid>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentPresenter ContentTemplate="{StaticResource myTemplate}"/>
</Grid>
Answer is to long for comment
Arnaud Weil brought me on the right way:
To access the Property 'IsAdministrator' in ViewModel from the Datatemplate, I gave the UserControl a Name e.g.:
<UserControl
x:Class="blanked out"
x:Name="this"
Used the code from Arnaud with some modifications, to inherit the Binding to the ViewModel from UserControl
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<helper:NotBooleanToVisibilityConverter x:Key="NotBooleanToVisibilityConverter"/>
<DataTemplate x:Key="myTemplate">
<Grid>
<Grid Visibility="{Binding DataContext.IsAdministrator, ElementName=this, Converter={StaticResource BooleanToVisibilityConverter}}">
<!-- Content for admin -->
<TextBlock Background="Yellow" Margin="3" Text="ICH BIN ADMNIN; JUCHUUU" />
</Grid>
<Grid Visibility="{Binding DataContext.IsAdministrator, ElementName=this, Converter={StaticResource NotBooleanToVisibilityConverter}}">
<!-- Content for user -->
<Image
Name="logo"
Source="/blanked out"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</Grid>
</DataTemplate>
</UserControl.Resources>
And for the inverted BooleanToVisibilityConverter:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace blankedout.Helper
{
[ValueConversion(typeof(bool), typeof(Visibility))]
public class NotBooleanToVisibilityConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var boolValue = (bool)value;
return !boolValue ? Visibility.Visible : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Thanks once again to Arnaud Weil
Regards