Switch between Views according to TreeView SelectedItem - wpf

i can't find a solution to this problem.
i have a treeview, and i'm trying to get to the point where i'm clicking/double clicking and it opens a view on a different part of the window(lets say using a gridsplitter and the tree is on the right and the relevant view will open on the left by setting the contentcontrol content DP).
thanks

I used
Simplifying the WPF TreeView by Using the ViewModel Pattern
to build my Treeview.
my xaml looks like :
<TreeView ItemsSource="{Binding Parents,IsAsync=True}" Name="tree" SelectedItemChanged="tree_SelectedItemChanged" Background="Transparent" >
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:XMLParentViewModel}"
ItemsSource="{Binding Children}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="500"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition MinHeight="20" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding ParentDisplayText}" TextWrapping="Wrap"/>
</Grid>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:XMLChildViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="500"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition MinHeight="20" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding ChildDisplayText}" TextWrapping="Wrap" MouseDown="TextBlock_PreviewMouseDown" />
</Grid >
</DataTemplate>
</TreeView.Resources>
</TreeView>
and the to know what kind of element is selected :
private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if( tree.SelectedItem.GetType() == typeof(XMLChildViewModel))
//Do what you need
}
I can adapt this code for you but if you have more questions

What clemens said, but also I have a hard time understanding what the problem/issue is? All the help we can get understanding your question, will make all the help you get even better :)

I think This will help. Here the XAML Code...
<TreeView Name="treenavigator" Grid.Row="1">
<TreeViewItem DisplayMemberPath="Item" Header="Item" Name="navitem">
<TreeViewItem Header="Add Item" Name="additem" />
<TreeViewItem Header="Update Item Details" Name="updateitem" />
<TreeViewItem Header="View Item Details" Name="viewitemdetails" />
<TreeViewItem Header="Delete Items" Name="deleteitem" />
</TreeViewItem>
</TreeView>
Here the Sample C# Code. grdForm is the grid in main window that I load the User Controller, and AddItem is the User Controller That I load into grdForm.
private void navitem_Selected(object sender, RoutedEventArgs e)
{
if (treenavigator.SelectedValue.ToString() == additem.ToString())
{
AddItem ItemView = new AddItem();
grdform.Children.Add(ItemView);
}
}

Related

WPF: Fast auto-sizing by height grid

I have to implement window containing several tables into one scroll viewer. This means that this tables should be stretched by the content. User able to add / remove items (rows) to these tables.
The concept was shown on the following mockup. The main problem is that grid should not have scroll bar, it should have dynamic height.
For the moment this interface is implemented as ItemsControl inside the ScrollViewer. In the ItemTemplate of the ItemsControl added DataGrid to represent tabular data.
<ScrollViewer CanContentScroll="True"
HorizontalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Path=Groups}"
VirtualizingStackPanel.IsVirtualizing="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="125" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0"
Style="{StaticResource ResourceKey=LabelBaseStyle}"
Content="{Binding Path=GroupLabel}"
HorizontalAlignment="Right"/>
<Button Content="{x:Static Member=Resources:CommonStrings.Delete}"
Style="{StaticResource ResourceKey=ButtonBaseStyle}"
VerticalAlignment="Center" />
<DataGrid Grid.Row="0" Grid.Column="1"
AutoGenerateColumns="False"
ItemsSource="{Binding Path=Items}">
<DataGrid.Columns>
<!-- 21 text columns here -->
</DataGrid.Columns>
</DataGrid>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
This solution works fine until some amount of data has been added. Now on the 7 tables (grids) with about 50 items in the each the application is impossible slow: it takes several minutes to render it. After profiling I've found that almost all the time is spent on Measure and Arrange methods. Also I've found recomentation to not to use DataGrid into contrainers which measures it with infinity. So I undestand the problem, but I cannot change interface.
I've tried to write the same interface without DataGrid: replaced it by ItemsControl with TextBlocks. This solution works fine. But I've several similar interfaces and it's not looks very good to write so much similar code. The code shown below is replacement for DataGrid in previous sample:
<ItemsControl ItemsSource="{Binding Path=Items}"
VirtualizingStackPanel.IsVirtualizing="True"
Grid.Row="0" Grid.Column="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Type}" />
<!-- Another 20 TextBlocks here -->
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
So I need to implement own UserControl or find one ready to use.
Can anyone suggest me something? Maybe some workaround or lightweight control?
Re-did my answer....this is a better solution for your issue. I'm sure you can figure out how to modify this to work:
In my Main Window Xaml:
<ScrollViewer Height="Auto" Width="Auto" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Visible">
<StackPanel Height="Auto" Width="Auto">
<ItemsControl ItemsSource="{Binding ItemList}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type wpfmvvmtest:itemTypeA}">
<wpfmvvmtest:testUC></wpfmvvmtest:testUC>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
</StackPanel>
</ScrollViewer>
Here's the Main ViewModel for the Main Window (testVM) all done in constructor for example:
public testVM()
{
ItemList = new ObservableCollection<object>();
Random rnd = new Random();
for (int i = 0; i < 3; i++)
{
itemTypeA item = new itemTypeA(rnd.Next(100));
ItemList.Add(item);
}
}
public ObservableCollection<object> ItemList { set; get; }
and here's what "itemTypeA" is like:
public itemTypeA(int count)
{
Items = new DataTable();
Items.Columns.Add("One");
Items.Columns.Add("Two");
Items.Columns.Add("Three");
Items.Columns.Add("Four");
Description = "Count = " + count;
for (int i = 0; i < count; i++)
{
DataRow dr = Items.NewRow();
dr[0] = i*1;
dr[1] = i * 2;
dr[2] = i * 3;
dr[3] = i * 4;
Items.Rows.Add(dr);
}
}
public DataTable Items { set; get; }
Here's the important part(Make sure you have no height/width properties set in your UserControl for the DataTemplate (That allows for the DataGrid to set the height/width):
<UserControl x:Class="wpfmvvmtest.testUC"
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"
d:DataContext="d:designInstance itemTypeA"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" HorizontalAlignment="Stretch" Content="{Binding Description}"></Label>
<Border Grid.Row="1" BorderBrush="Black" BorderThickness="2">
<DataGrid ItemsSource="{Binding Path=Items}">
</DataGrid>
</Border>
</Grid>
</UserControl>

Why is my WPF ContextMenu Item disabled?

I have a small but annoying problem with my ContextMenu in a WPF application.
I use a DataTemplate for my List of ViewModel-objects to create the visual elements. In the DataTemplate I simply set my UserControl like this:
<!-- Define a data-template for the 'RoomViewModel' class. This generates the UI for each node. -->
<DataTemplate DataType="{x:Type model:RoomViewModel}">
<network:RoomView network:ConstraintView.ArgumentChanged="ConstraintView_ArgumentChanged"></network:RoomView>
</DataTemplate>
I want the RoomView to have a ContextMenu where a RelayCommand should be executed if the user clicks on the MenuItem. My UserControl for the RoomView looks like this at the moment:
<UserControl x:Name="userControl" x:Class="NetworkUI.RoomView"
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:network="clr-namespace:NetworkUI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContextChanged="userControl_DataContextChanged">
<UserControl.Resources>
<!-- UI commands -->
<RoutedCommand x:Key="Commands.NewConstraintCmd"></RoutedCommand>
</UserControl.Resources>
<UserControl.CommandBindings>
<CommandBinding x:Name="newConst" Command="{StaticResource Commands.NewConstraintCmd}" Executed="NewConstraint_Executed"></CommandBinding>
</UserControl.CommandBindings>
<Grid Width="Auto" Height="Auto" MinWidth="50" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Width="Auto" Height="20" MinWidth="50" >
<Rectangle Stroke="Black" Fill="White" RadiusX="4" RadiusY="4" SnapsToDevicePixels="True" ></Rectangle>
<Grid Margin="-4" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="10" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<network:EditableTextBlock Grid.Column="1" Grid.Row="1" x:Name="nameTextBox" Text="{Binding Name, Mode=TwoWay}" HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="{x:Null}" />
<network:ConnectorItem Grid.Row="1" Grid.Column="0" DataContext="{Binding Connectors[0]}" />
<network:ConnectorItem Grid.Row="1" Grid.Column="2" DataContext="{Binding Connectors[1]}" />
</Grid>
</Grid>
<StackPanel Grid.Row="1" x:Name="roomProperties" Width="Auto" HorizontalAlignment="Stretch" >
<ItemsControl ItemsSource="{Binding PropertyGroups}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<network:ConstraintCollectionView></network:ConstraintCollectionView>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
<UserControl.ContextMenu>
<ContextMenu x:Name="contextMenu">
<MenuItem Header="new Constraint" Command="{StaticResource Commands.NewConstraintCmd}"></MenuItem>
</ContextMenu>
</UserControl.ContextMenu>
</UserControl>
I am not really sure if my UserControl code is ok. In my CodeBehind file I define a
public ICommand NewConstraintCmd;
-Command that should be executed when the user clicks the Item. My Executed handler is simple and looks like this:
private void NewConstraint_Executed(object sender, ExecutedRoutedEventArgs e) {
ViewModel.AddConstraint();
}
The ViewModel is indeed a RoomViewModel and the NewConstraintCmd is set in the DataContextChanged - event (not displayed here).
My simple question is, why is my ContextMenu-Item always disabled? I mean the RelayCommand.CanExecute is never checked, is this the problem maybe?
I didn't find any solution for my problem yet.
Thank you for any help!
Thank you Rohit Vats! I changed my ICommand definition to this:
public static readonly ICommand NewConstraint = new RelayCommand((rvm) => AddConstraint(rvm));
Since this is a static method I needed the parameter (the DataContext of my RoomView).
My Method is defined like this now:
private static void AddConstraint(object rvm) {
if (rvm is RoomViewModel)
(rvm as RoomViewModel).AddConstraint();
}
So first the parameter is checked and if it is ok (a RoomViewModel object) I call the actual function on the object.
I have no idea why it works now, really :/.
My XAML code for the MenuItem now looks like this:
<MenuItem Header="new Constraint" Command="network:RoomView.NewConstraint" CommandParameter="{Binding}"></MenuItem>
As mentioned before I need the CommandParameter to call a function on it. Since the needed Object is my DataContext I just use the {Binding} to pass the object.
This really works fine now, I hope it will work with InputBindings as well in the future :)!
Thank you again for the help!

How can I get SelectedItem and show Headers using ItemsControl?

I am working on WPF Windows Application. I'm using ItemsControl to show collection list. Working on this I found there is no SelectedItem property in ItemsControl. Then how can I get the Selected Item from the ItemsControl. And also How can I display the Headers of ItemsControl.
<ItemsControl ItemsSource="{Binding CustomSalesProducts, Mode=TwoWay}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsPresenter/>
</ScrollViewer>
</Border>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel CanHorizontallyScroll="True" CanVerticallyScroll="True" Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="SalesGrid" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<controls:HeaderedContentControl Header="{Binding ProductName, Mode=TwoWay}" Margin="{DynamicResource Margin4}" Style="{DynamicResource HeaderedContentControlStyle}" HorizontalContentAlignment="Right">
</controls:HeaderedContentControl>
<TextBox Text="{Binding OrderQty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Margin="{StaticResource Margin4}" Style="{DynamicResource MiniTextBoxStyle}" ToolTip="Quantity" />
<TextBlock Text="{Binding UnitSalePrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="1" Margin="{StaticResource Margin4}" ToolTip="Price"/>
<TextBox Text="{Binding Discount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="2" Grid.Row="1" Margin="{StaticResource Margin4}" Style="{DynamicResource MiniTextBoxStyle}" ToolTip="Discount"/>
<TextBlock Text="{Binding TaxAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.Row="1" Margin="{StaticResource Margin4}" ToolTip="Tax Amount"/>
<TextBlock Text="{Binding LineTotal, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="4" Grid.Row="1" Margin="{StaticResource Margin4}" ToolTip="Total"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Thanks,
As you said there is no SelectedItem in the ItemsControl. You can use ListBox instead.
A bit late to the party, but I came across the same problem, and in the hopes that this can help someone else here's how I rolled my own SelectedItem since I didn't want to use a ListBox.
You could expose a SelectedCustomSalesProduct property to the class you are using as your DataContext, and then you can keep track of the selected item yourself by setting it when the item is selected.
In your SalesGrid, you could add event handlers for the MouseLeftButtonDown and for the TouchDown events, and use the Tag property to keep a reference to the item being rendered as such:
Please note that in my case, I was using a StackPanel instead of a Grid, and I didn't compile the code below, use it for illustrative purposes.
By using this example you should be able to get the general idea and set the Selected item in your business service.
<DataTemplate>
<Grid x:Name="SalesGrid" Background="White"
Tag="{Binding}"
TouchDown="DataTemplate_Touch"
MouseLeftButtonDown="DataTemplate_Click">
Then in your UserControl/window's code behind you can keep track of the selected item as such:
/// <summary>
/// MyScreen.xaml
/// </summary>
public partial class MyScreen : UserControl
{
private MyServiceWrapper _serviceWrapper;
public MyScreen()
{
InitializeComponent();
}
public MyScreen(MyServiceWrapper serviceWrapper)
{
//Instrumentation.Log(typeof(MyScreen), LogTypes.Trace, "Creating instance of MyScreen");
this._serviceWrapper = serviceWrapper;
// Set your DataContext, is this the class that would also have your
// CustomSalesProducts property exposed
this.DataContext = this._serviceWrapper;
InitializeComponent();
}
private void DataTemplate_Touch(object sender, System.Windows.Input.TouchEventArgs e)
{
SetSelectedCustomSalesProduct(sender);
}
private void DataTemplate_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
SetSelectedCustomSalesProduct(sender);
}
private void SetSelectedCustomSalesProduct(object sender)
{
_serviceWrapper.SelectedCustomSalesProduct = ((Grid)sender).Tag as CustomSalesProduct;
}
}
I found that for using headers there is HeaderdItemsControl. With this I can add headers and also it is not repeatable. But problem with this is that we have to define static size for header and its item if we define auto size then the UI of headeredItemsControl is not perfect so we have to give its static size.
You can read this for how to use HeaderedItemsControl?

2 identical Controls in the same Grid ? (WPF/xaml)

Here is a simple code that exposes my problem :
<Grid>
<TreeView Name="myTreeViewEvent" >
<TreeViewItem Header="Employee1"/>
</TreeView>
<TreeView Name="myTreeViewEvent2" >
<TreeViewItem Header="Employee2"/>
</TreeView>
</Grid>
The thing is that my 2nd Treeview "overwrites" the 1st one...
Is there a way to change the behaviour so that the 2nd Treeview is "added" to the 1st one ?
(nb : no, I can't put them in the same Treeview cause in my "real" code, I got 2 different Treeviews that I CAN'T merge... and I gotta display them in the same grid !)
Try this
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TreeView Name="myTreeViewEvent" >
<TreeViewItem Header="Employee1"/>
</TreeView>
<TreeView Grid.Row="1" Name="myTreeViewEvent2" >
<TreeViewItem Header="Employee2"/>
</TreeView>
</Grid>
EDIT
Then what prevents you from using this approach?
<Grid>
<StackPanel>
<TreeView Name="myTreeViewEvent">
<TreeViewItem Header="Employee1"/>
</TreeView>
<TreeView Name="myTreeViewEvent2">
<TreeViewItem Header="Employee2"/>
</TreeView>
</StackPanel>
</Grid>
In this case there is no strict division. The items will strech up.

Binding nested control using MVVM pattern

I have a problem with binding nested control with my MVVM pattern. This is my XAML code:
<ItemsControl Grid.Column="1" ItemsSource="{Binding NotificationContacts}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<toolkit:Expander>
<toolkit:Expander.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ContactName}" Grid.Column="0" VerticalAlignment="Center"></TextBlock>
<Image Source="Images/answer_ok.png" Grid.Column="1" Margin="15,0,15,0" Width="27" Height="27"></Image>
</Grid>
</toolkit:Expander.Header>
<toolkit:Expander.Content>
<ListBox Margin="30,10,0,10" ItemsSource="{Binding NotificationContacts.Messages">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MessageName}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</toolkit:Expander.Content>
</toolkit:Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
The problem is, that the listbox control located in ExpanderControl Data Template is not being data bound.
Listbox control is populated by EntityCollection named 'Messages' which is contained in parent object 'NotificationContacts' that ItemsControl is databound with...
Does anyone know how to resolve this issue ?
Thanks in advance !!!
Did you try this:
<ItemsControl Grid.Column="1" ItemsSource="{Binding NotificationContacts}">
......
<ListBox Margin="30,10,0,10" ItemsSource="{Binding Messages}">
.....
<TextBlock Text="{Binding MessageName}"></TextBlock>
If I remember it right, when you are "inside" ItemContol, binding context is set to NotificationContacts. So use just "{Binding Messages}" could be fine.
And by the way, you are missing curly bracket on the line:
<ListBox Margin="30,10,0,10" ItemsSource="{Binding NotificationContacts.Messages">
Call ItemsControl f.i. "ic" and use next binding in ListBox
<ItemsControl x:Name="ic" Grid.Column="1" ItemsSource="{Binding NotificationContacts}">
...
<ListBox Margin="30,10,0,10" ItemsSource="{Binding ElementName=ic, Path=DataContext.Messages}">

Resources