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>
Related
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.
I am trying to get Drag and Drop working with WinUI3. In WPF I used to add added both AllowDrop and Drop to a UI element and I was able to receive the filename of a dropped file. However in WinUI3 the method Drop is not beeing executed. What am I doing wrong?
XAML
<Page
x:Class="..."
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="..."
xmlns:helper="..."
xmlns:prop="..."
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<DataTemplate x:Key="Image" x:DataType="helper:ProductImage">
<Border BorderBrush="{x:Bind Path=Color, Mode=OneWay}" BorderThickness="1" Background="Transparent"
AllowDrop="True" Drop="Image_Drop" >
<Grid Width="{Binding ElementName=PIImageSize, Path=Value}"
Height="{Binding ElementName=PIImageSize, Path=Value}" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="2" HorizontalAlignment="Center"
Text="{x:Bind Path=Type, Mode=OneWay}"
Foreground="{x:Bind Path=Color, Mode=OneWay}" />
<Image Grid.Row="1" Stretch="Uniform" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Source="{x:Bind Path=BitmapImage, Mode=OneWay}"/>
<TextBox Grid.Row="2" Text="{x:Bind Path=Path, Mode=TwoWay}" />
</Grid>
<Border.ContextFlyout>
</Border.ContextFlyout>
</Border>
</DataTemplate>
</Page.Resources>
...
</Page>
Code
private void Image_Drop(object sender, DragEventArgs e)
{
// Function is not executed
}
You also have to add the DragOver event, to accept the operation:
private void Image_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
}
I have view with a combobox and five textboxes which is used to add new customer. To add the customer, declared the properties in my viewmodel and bind those properties to all respective textboxes text properties like,
View:
<StackPanel>
<ComboBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomers}" DisplayMemberPath="Name"/>
<Textbox Text="{Binding Name}"/>
<Textbox Text="{Binding Age}"/>
<Textbox Text="{Binding Phone}"/>
<Textbox Text="{Binding Address}"/>
<Textbox Text="{Binding Email}"/>
<StackPanel>
ViewModel:
public class myviewmodel
{
private string _name;
public string Name
{
get { return _name;}
set { _name = value; OnPropertyChanged("Name"); }
}
private string _age;
public string Age
{
get { return _age;}
set { _age = value; OnPropertyChanged("Age"); }
}
private Customer _selectedCustomer;
public Customer SelectedCustomer
{
get { return _selectedCustomer; }
set { selectedCustomer = value; OnPropertyChanged("SelectedCustomer"); }
}
}
I will load the existing customer names to the comboxbox. To update the existing
customer details, if i select a customer name in combobox the selected customer details
should bind in textboxes so that i can easily update them. but the textbox text
properties are already used to add the new customers. so how to add and update the
customers using the same textboxes??
The Textboxes' Bindings are not set to the SelectedCustomer. Give this a try.
<ComboBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomer}" DisplayMemberPath="Name"/>
<Grid Visibility="{Binding ExistingCustomer, Converter={StaticResource VisibilityConverter}}">
<Textbox Text="{Binding SelectedCustomer.Name, Mode=TwoWay}"/>
<Textbox Text="{Binding SelectedCustomer.Age, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Phone, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Address, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Email, Mode=TwoWay}}"/>
</Grid>
<Grid Visibility="{Binding ExistingCustomer, Converter={StaticResource VisibilityConverter}}">
<Textbox Text="{Binding Customer.Name, Mode=TwoWay}"/>
<Textbox Text="{Binding Customer.Age, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Phone, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Address, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Email, Mode=TwoWay}}"/>
</Grid>
And here is the code for the converter
public class VisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string culture)
{
bool displayControl = (bool)value;
if (displayControl == true)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
return null;
}
}
Be sure to reference the namespace where your converter lives in your page resources
Using Interaction Behaviors this can be achieved.
First of all, the Behaviors SDK is not built-in UWP, but has to be downloaded separately from NuGet.
You can use the following command to install it:
Install-Package Microsoft.Xaml.Behaviors.Uwp.Managed
Or just use the NuGet Package Manager and search for Microsoft.Xaml.Behaviors.Uwp.Managed.
After you install, you can just add the XAML using statements to the top of your page:
<Page ...
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core" />
You do not need to create another property SelectedCustomer if you are always going to bind your TextBox from Combobox SelectedItem. Unless you intend to use SelectedCustomer for some other code behind work.
Below is how you achieve your TextBox Text without SelectedCustomer Property.
<ComboBox x:Name="comboBox" ItemsSource="{Binding Customers}" DisplayMemberPath="Name" HorizontalAlignment="Stretch" Margin="5,0">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding SelectedItem, ElementName=comboBox}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</ComboBox>
<StackPanel Orientation="Vertical" Grid.Row="1" Margin="5,20" DataContext="{Binding SelectedItem, ElementName=comboBox}">
<TextBox Text="{Binding Name, Mode=TwoWay}" PlaceholderText="Name" Name="Name"/>
<TextBox Text="{Binding Age, Mode=TwoWay}" PlaceholderText="Age" Name="Age"/>
<TextBox Text="{Binding Phone, Mode=TwoWay}" PlaceholderText="Phone" Name="Phone"/>
<TextBox Text="{Binding Address, Mode=TwoWay}" PlaceholderText="Address" Name="Address"/>
<TextBox Text="{Binding Email, Mode=TwoWay}" PlaceholderText="Email" Name="Email"/>
</StackPanel>
If you notice, I bound the data from comboBox SelectedItem Property to StackPanel DataContext and then Individual Properties directly to Text of your TextBox. This will take care of your ComboBox Binding to TextBox. Mode should always be TwoWay so that data can be updated when user Modifies Existing Customer Details.
Now after this is done, When you want to add a new Customer Info with current TextBoxes, You want to clear the selection without changing the current value. Below is how I added a Button with Interaction Behaviors.
And use the Clicked action to clear the TextBox Text. In UWP XAML you can use empty string as value and it works as expected.
<Button Content="+" Grid.Column="1" Margin="5,0" Tag="{Binding EmptyClass, Mode=TwoWay}" Name="btnNew">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Click">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding Tag, ElementName=btnNew, Mode=TwoWay}" />
<core:ChangePropertyAction TargetObject="{Binding ElementName=comboBox}" PropertyName="SelectedIndex" Value="-1" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</Button>
Also Note I am making the selected Index of ComboBox to -1 so that selected Data cannot be updated.
And now the saving portion should be pretty simple and straight forward. Below is a button that i used with TappedEvent
private void saveBtn_Tapped(object sender, TappedRoutedEventArgs e)
{
model.Customers.Add(model.EmptyClass);
model.EmptyClass = new MyClass();
}
You can see I am reinstantiating EmptyClass Again so that old bound data can be cleared off.
Below is Complete XAML
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App15"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Text="using:System.Text"
x:Class="App15.MainPage"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
Loaded="Page_Loaded"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="0,100,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="comboBox" ItemsSource="{Binding Customers}" DisplayMemberPath="Name" HorizontalAlignment="Stretch" Margin="5,0">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding SelectedItem, ElementName=comboBox}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</ComboBox>
<Button Content="+" Grid.Column="1" Margin="5,0" Tag="{Binding EmptyClass, Mode=TwoWay}" Name="btnNew">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Click">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding Tag, ElementName=btnNew, Mode=TwoWay}" />
<core:ChangePropertyAction TargetObject="{Binding ElementName=comboBox}" PropertyName="SelectedIndex" Value="-1" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</Button>
</Grid>
<StackPanel Orientation="Vertical" Grid.Row="1" Margin="5,20" Name="stkData">
<TextBox Text="{Binding Name, Mode=TwoWay}" PlaceholderText="Name"/>
<TextBox Text="{Binding Age, Mode=TwoWay}" PlaceholderText="Age" />
<TextBox Text="{Binding Phone, Mode=TwoWay}" PlaceholderText="Phone" />
<TextBox Text="{Binding Address, Mode=TwoWay}" PlaceholderText="Address" />
<TextBox Text="{Binding Email, Mode=TwoWay}" PlaceholderText="Email" />
</StackPanel>
<Button Name="saveBtn" Content="Save" HorizontalAlignment="Stretch" Margin="5" Grid.Column="1" Grid.Row="2" Tapped="saveBtn_Tapped"/>
</Grid>
</Grid>
</Page>
Below is Complete Code Behind
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace App15
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
MyViewModel model = new MyViewModel();
private void Page_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = model;
}
private void saveBtn_Tapped(object sender, TappedRoutedEventArgs e)
{
model.Customers.Add(model.EmptyClass);
model.EmptyClass = new MyClass();
}
}
}
Below is Complete View Model
public class MyViewModel
{
public MyViewModel()
{
Customers = new ObservableCollection<MyClass>();
EmptyClass = new MyClass();
for (int i = 0; i < 10; i++)
{
Customers.Add(new MyClass()
{
Name = "Item" + (i + 1).ToString(),
Address = "Address" + (i + 1).ToString(),
Age = "20" + (i + 1).ToString(),
Email = "Test" + (i + 1).ToString() + "#test.com",
Phone = (9876543210 + i).ToString()
});
}
}
public ObservableCollection<MyClass> Customers { get; set; }
public MyClass EmptyClass { get; set; }
}
public class MyClass
{
public string Name { get; set; }
public string Age { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
I know there is a way to even use Save Option in MVVM But I did not get the opportunity to use DelegateCommand. But if you would like to try it yourself, Check this Video by Jerry Nixon for Reference
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
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();
}