Own DataTemplateSelector MVVM - 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

Related

Xamarin forms same listview in different views [duplicate]

I have written a nice Grid with some other controls like: Entry and Image and now I would like to reuse it the simplest way.
This is my control for Email property:
<Grid
Style="{StaticResource gridEntryStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="9*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="7" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<controls:ExtendedEntry
Grid.Row="0"
Grid.Column="0"
Text="{Binding UserEmail, Mode=TwoWay}"
Placeholder="{i18n:Translate UserEmailPlaceholder}"
Style="{StaticResource entryStyle}">
<controls:ExtendedEntry.Behaviors>
<behavior:EventToCommandBehavior
EventName="Focused"
Command="{Binding ControlFocusCommand}"
CommandParameter="UserEmail"/>
<behavior:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding ControlUnfocusedCommand}"
CommandParameter="UserEmail"/>
</controls:ExtendedEntry.Behaviors>
</controls:ExtendedEntry>
<Image
Grid.Row="0"
Grid.Column="1"
Source="clear.png"
IsVisible="{Binding IsEntryFocused}"
Style="{StaticResource imageClearStyle}">
<Image.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding ClearCommand}"
CommandParameter="UserEmail"/>
</Image.GestureRecognizers>
</Image>
<Image
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Source="lineWhite.png"
Style="{StaticResource imageLineStyle}"/>
<Image
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Source="linePure.png"
Style="{StaticResource imageLineStyle}"
IsVisible="{Binding IsError}"/>
<Image
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Source="lineGradient.png"
Style="{StaticResource imageLineStyle}"
IsVisible="{Binding IsEntryFocused}"/>
<Label
Grid.Row="2"
Grid.Column="0"
Text="{Binding ErrorMessage}"
Style="{StaticResource labelErrorStyle}"
IsVisible="{Binding IsError}"/>
<Image
Grid.Row="2"
Grid.Column="1"
Source="error.png"
Style="{StaticResource imageErrorStyle}"
IsVisible="{Binding IsError}"/>
</Grid>
I would like to reuse it for example as follows:
<usercontrols:EntryControl
MainText="{Binding UserEmail}"
MainTextPlaceholder="{i18n:Translate UserEmailPlaceholder}" />
For now even this simple example is not working and I have no idea how to define Command in this control. For now I have:
public partial class EntryControl : ContentView
{
public EntryControl()
{
InitializeComponent();
}
public static readonly BindableProperty MainTextProperty =
BindableProperty.Create(
propertyName: "MainText",
returnType: typeof(string),
declaringType: typeof(string),
defaultValue: string.Empty,
defaultBindingMode: BindingMode.TwoWay);
public string MainText
{
get { return (string)this.GetValue(MainTextProperty); }
set { this.SetValue(MainTextProperty, value); }
}
public static readonly BindableProperty MainTextPlaceholderProperty =
BindableProperty.Create(
propertyName: "MainTextPlaceholder",
returnType: typeof(string),
declaringType: typeof(string),
defaultValue: string.Empty,
defaultBindingMode: BindingMode.TwoWay);
public string MainTextPlaceholder
{
get { return (string)this.GetValue(MainTextPlaceholderProperty); }
set { this.SetValue(MainTextPlaceholderProperty, value);}
}
}
Is this the right way? or is this even possible in Xamarin.Forms?
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ApplicationName.Controls.EntryControl"
Style="{StaticResource gridEntryStyle}">
</Grid>
xaml.cs:
namespace ApplicationName.Controls
{
public partial class EntryControl : Grid
{
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(
propertyName: nameof(Command),
returnType: typeof(ICommand),
declaringType: typeof(EntryControl),
defaultValue: null,
defaultBindingMode: BindingMode.TwoWay);
public string Command
{
get { return (string)this.GetValue(CommandProperty); }
set { this.SetValue(CommandProperty, value); }
}
public EntryControl()
{
InitializeComponent();
}
}
}
using:
xmlns:controls="clr-namespace:ApplicationName.Controls;assembly=ApplicationName"
<controls:EntryLabel/>
Your issue with BindingContext
In short, you have to write down the bindings inside your control like this {Binding UserEmail, Mode=TwoWay, Source={x:Reference myControlTHIS}}, where 'myControlTHIS' is x:Name="TheCategoryHeader".
More info:
BindingContext is everything when it comes to getting things to bind and work right in an MVVM app – WPF or Xamarin. Controls inherit context from the parent control unless a different context is explicitly assigned. That’s what we need to do here. We need to tell each UI element (label, entry, button, etc.) to explicitly look at this control for its context in order to find those BindingProperties we just made. This is one of the rare occasions when we actually give a XAML element a name: When it is going to be referenced by another XAML element within the XAML itself. To the ContentView, add a tag naming the control ‘this’. That’s right. We’re going to keep to the Microsoft naming and have this item refer to itself as 'myControlTHIS'. It makes all of us comfortable and the code and markup easy to read and follow.
We can now use 'myControlTHIS' as a reference source telling the rest of our XAML where to look for properties to bind to.

MVVM event handling

I am trying to manage dragdrop events on a "TreeView" object in a view with MVVM approach, thus I don't want write hookevent codes in "FormProjectWorksView.xaml.cs"... And following a tutorial on youtube : https://www.youtube.com/watch?v=Cx6YE86XzYE , I tried to get a custom dependency property being populated in xaml designer code in visual studio...But when I type the name of the customDP which is "DragCommand"; it doesn't get recognised, anywhere in the "xaml" file... In my case I tried to use it inside "" Tag..could you help why it doesn't showup in the IDE popup? and doesn't compile of course? Or am I totally in wrong direction to handle such mouseevents on a view separated from viewmodel...And even further actually I am using view switching from MainWindow.xml, which is the starting View of the application...and any other "UserControl-Views" are switched when necessary.
FormProjectWorksView.xaml
<UserControl x:Class="FullProject.Views.FormProjectWorksView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:FullProject.Views"
xmlns:viewmodels="clr-namespace:FullProject.ViewModels"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<TreeView x:Name="tv1" Grid.Column="0" ItemsSource="{Binding treeView.Items}"
AllowDrop="True"/>
<Grid x:Name="maingrid" Grid.Column="1" Background="Chartreuse">
<TextBlock Grid.Column="0" Margin="10 " Text="{Binding deneme}" FontSize="28"/>
</Grid>
</Grid>
</UserControl>
FormProjectWorksView.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace FullProject.Views
{
/// <summary>
/// Interaction logic for FormProjectWorksView.xaml
/// </summary>
public partial class FormProjectWorksView : UserControl
{
public ICommand DragCommand
{
get { return (ICommand)GetValue(DragCommandProperty); }
set { SetValue(DragCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DragCommandProperty =
DependencyProperty.Register("DragCommand", typeof(ICommand), typeof(FormProjectWorksView), new PropertyMetadata(null));
public FormProjectWorksView()
{
InitializeComponent();
}
}
}
MainWindow.xaml
<Window x:Class="FullProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FullProject"
xmlns:viewmodels="clr-namespace:FullProject.ViewModels"
xmlns:views="clr-namespace:FullProject.Views"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type viewmodels:MainFormViewModel}">
<views:MainFormView/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:GlobalWorksViewModel}">
<views:GlobalWorksView/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:GlobalResourcesViewModel}">
<views:GlobalResourcesView/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:FormProjectWorksViewModel}">
<views:FormProjectWorksView/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding CurrentViewModel}"/>
</Grid>
</Window>

How to reference converter in a ResourceDictionary file

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

How to bind a combobox having an item as a datagrid in wpf? The ComboBox itself is a part of a Datatemplate

I have a TabControl generating some tab items following the MVVM pattern using WPF.
The TabControl ItemTemplate i.e. for each of the tab items that is generated, I have a combobox that should show some data from a different list. This list is not the same as the bound object of the Tab Item itself.
For eg: If a tabitem is bound to a address object the combobox should show data from a state list and show the state present in the address object as the selected item.
The Combo box is having only one item as a datagrid which is bound to the state list
The problem is that all data is being shown in all sections but the combo box simply wouldnt show the data. Surprisingly, the Combobox when taken out of the TabControl DataTemplate works fine....
Below is the code both outside and inside the tabcontrol. Some suggestions please !!!
------This one is outside the Tabcontrol and works perfectly--------------
<ComboBox SelectedValue="{Binding SelectedState}" HorizontalAlignment="Left" VerticalAlignment="Center" IsEditable="True" Margin="50,55,0,61" Height="27" Width="193">
<ComboBoxItem TextSearch.Text="{Binding SelectedState}">
<ContentControl>
<DataGrid SelectedIndex="{Binding StateSelectedIndex}" ItemsSource="{Binding StateData}" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" cal:Message.Attach="[Event SelectionChanged] = [Action SelectionChanged]">
<DataGrid.Columns>
<DataGridTextColumn Header="StateName" Binding="{Binding StateName}" />
</DataGrid.Columns>
</DataGrid>
</ContentControl>
</ComboBoxItem>
</ComboBox>
----This one is inside the TabControl ---------
<TabControl Margin="3,3,0,0" HorizontalAlignment="Left" Width="752" Height="255" VerticalAlignment="Top" Grid.ColumnSpan="2" Grid.Row="1" ItemsSource="{Binding Addresses}" SelectedIndex="{Binding WhichAddressTab}" >
<TabControl.ItemContainerStyle>
...................................
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl>
..........................
<ComboBox SelectedValue="{Binding SelectedState}" HorizontalAlignment="Left" VerticalAlignment="Center" IsEditable="True" Margin="108,3,0,1" Grid.ColumnSpan="3" Grid.Row="1" Width="147">
<ComboBoxItem TextSearch.Text="{Binding SelectedState}" >
<ContentControl>
<DataGrid SelectedIndex="{Binding StateSelectedIndex}" ItemsSource="{DynamicResource StateData}" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" cal:Message.Attach="[Event SelectionChanged] = [Action SelectionChanged]">
<DataGrid.Columns>
<DataGridTextColumn Header="StateName" Binding="{Binding StateName}" />
</DataGrid.Columns>
</DataGrid>
</ContentControl>
</ComboBoxItem>
</ComboBox>
...........................
</Grid>
</ContentControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
I have tried searching and have understood the problem is with the databinding within a datatemplate, but have been unable to achieve the desired result.
Yes, the problem is with your binding. The DataContext inside of the DataTemplate is for a single element (from the collection bound to the ItemsSource). Meaning that you can't access properties that are directly on the ViewModel itself.
To work around this, you can name the TabControl for example, and convert your bindings inside of the DataTemplate to use ElementName bindings. Another solution, if you have your ViewModel defined as a Static Resource, is to bind directly to the resource, and use the Path to specify the property to which you want to bind.
Hope this helps :)

Treeview SelectedItem is sometimes the VM and sometimes TreeViewItem

I have a TreeView that the user navigates to select an item for display in a grid. Briefly the XAML looks like this:
<local:TreeViewEx x:Name="theTreeView" ItemsSource="{Binding theData}">
<local:TreeViewEx.ItemTemplate>
<sdk:HierarchicalDataTemplate ItemsSource="{Binding theChildData}">
<TextBlock Text="{Binding Name}"/>
</sdk:HierarchicalDataTemplate>
</local:TreeViewEx.ItemTemplate>
</local:TreeViewEx>
<Grid DataContext="{Binding ElementName=theTreeView, Path=SelectedItem}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding}" />
<TextBlock Text="{Binding Name}" /></StackPanel>
</Grid>
As the user clicks through the treeview the viewmodel type name is displayed along with the value of the Name property. Perfect. Howerver the user can also execute a search of the treeview (following to Josh Smith) which sets the IsSelected property of the TreeViewItem. Once that happens the {Binding} displays TreeViewItemEx rather than the ViewModel type name, and of course the Name property is not displayed.
How is that possible that the selectedItem would sometimes by the ViewModel, and sometimes be the TreeViewItem?
If you replace your grid with a ContentControl you can then use a DataTemplateSelector.
<ContentControl Content="{Binding ElementName=theTreeView, Path=SelectedItem}"
ContentTemplateSelector="{StaticResource TreeViewItemSelector}" />
On the DataTemplateSelector you can then reference two templates for the different types
<DataTemplate x:Key="ModelTemplate">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
<TreeViewItemSelector x:Key="TreeViewItemSelector"
ModelTemplate="{StaticResource ModelTemplate}"
TreeItemTemplate="{StaticResource TreeItemTemplate}" />
In the selector you will then want logic like this
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is ModelType)
return ModelTemplate;
if (item is TreeViewItem)
return TreeItemTemplate;
throw new NotImplementedException();
}