I have a TabControl. Each tab Item i.e newly added Tab is rendered using content template selector. But each time i switch between the tabs, content template selector is getting called.
I wanted to stop this. This is because, In the in Tabcontrol, User have provided actions to change the layout, since in the selection change event of the tab Item content template is getting called, it is getting difficult for me to retain the layout what user has changed during Tab Item Selection change Event.
Following is code i am using for the TabControl
<TabControl Grid.Column="2" x:Name="MainTabControl" HorizontalAlignment="Stretch" Margin="0,12,0,7"
SelectedItem="{Binding SelectedTabItem}"
Visibility="{Binding TabsVisible}"
ItemsSource="{Binding ToolsList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ItemTemplate="{StaticResource ToolDisplayDataTemplate}"
commands:FrameworkUICommandList.TabItemChangedCommand="{Binding Path=TabItemChangedCommand}"
>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding}" ContentTemplateSelector="{DynamicResource toolTabDataItemTemplateSelector}"/>
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem" BasedOn="{StaticResource TabItemStyle}">
<Setter Property="AutomationProperties.AutomationId" Value="{Binding ToolID}" />
<Setter Property="ToolTip" Value="{Binding ToolID,Converter={StaticResource ResourceKey=tabItemTooltipConverter}}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
UPDATE : I have created a sample project to explain my problem. Could not share the project anywhere, so updating the code snippet in main question. sorry for that.
In the sample project, user can add TabItem dynamically to TabControl. Eash Tabcontent can show two Grid panel and they are separated by Grid Splitter. Display of second grid is Based on some flag (in this example ShowSecondPanel). If user click on "Show / Hide Second Panel" button, then second panel content will be shown for the current selected tab.
The Problem is, user can re-size the panels using Grid Splitter, but when user navigates to some other tab and comes back to previous one, the grid splitter position changes to original position.
Hope I am clear on describing the problem.
Code for MainWindow.xaml
<Window x:Class="TabControlTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TabControlTestApp"
Title="MainWindow" Height="500" Width="700">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<local:TabContentTemplateSelector x:Key="tabContentTemplateSelector" />
<DataTemplate x:Key="TabitemDataTemplate">
<StackPanel Width="50" Height="50">
<TextBlock Text="{Binding TabFirstPanel.Name}"></TextBlock>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="TabContentWithFirstPanel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Name :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabFirstPanel.Name}"></TextBlock>
</Grid>
</DataTemplate>
<DataTemplate x:Key="TabContentWithBothPanel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Name :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabFirstPanel.Name}"></TextBlock>
</Grid>
<GridSplitter Grid.Row="0" Grid.Column="1"
VerticalAlignment="Stretch"
Width="5"
Height="Auto"
ResizeDirection="Columns"
ResizeBehavior="PreviousAndNext"
></GridSplitter>
<Grid Grid.Row="0" Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Additional Detail :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabSecondPanel.AdditionalDetails}"></TextBlock>
</Grid>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="1" Grid.Column="0">
<Button Content="Load Tab : 1" Name="LoadTab1" Width="100" Height="50" Command="{Binding LoadTabCommand}" CommandParameter="{Binding ElementName=LoadTab1}"></Button>
<Button Content="Load Tab : 2" Name="LoadTab2" Width="100" Height="50" Command="{Binding LoadTabCommand}" CommandParameter="{Binding ElementName=LoadTab2}"></Button>
<Button Content="Load Tab : 3" Name="LoadTab3" Width="100" Height="50" Command="{Binding LoadTabCommand}" CommandParameter="{Binding ElementName=LoadTab3}"></Button>
</StackPanel>
<Button Content="Close All tab" Width="100" Height="40" x:Name="CloseAllTab"></Button>
<Button Content="Show / Hide Second Panel" x:Name="ShowHideSecondPanelInTab"
Grid.Row="0" Grid.Column="1" Width="150"
Command="{Binding LoadTabCommand}" CommandParameter="{Binding ElementName=ShowHideSecondPanelInTab}"></Button>
<TabControl Grid.Row="1" Grid.Column="1"
ItemsSource="{Binding TabContentList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedTabItem}"
ItemTemplate="{StaticResource ResourceKey=TabitemDataTemplate}"
ContentTemplateSelector="{StaticResource ResourceKey=tabContentTemplateSelector}"
>
</TabControl>
</Grid>
</Window>
Code For MainWindowViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace TabControlTestApp
{
class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
this.loadTabCommand = new LoadTabCommand(this);
tabContentList = new ObservableCollection<TabContent>();
}
public ICommand LoadTabCommand
{
get
{
return this.loadTabCommand;
}
set
{
this.loadTabCommand = value;
}
}
public ObservableCollection<TabContent> TabContentList
{
get
{
return tabContentList;
}
set
{
tabContentList = value;
OnPropertyChanged("TabContentList");
}
}
public TabContent SelectedTabItem
{
get
{
return selectedTabItem;
}
set
{
selectedTabItem = value;
OnPropertyChanged("SelectedTabItem");
}
}
public void LoadFirstTab()
{
TabFirstPanel firstPanel = new TabFirstPanel() { Name = "John-1", Age = "31" };
TabSecondPanel secondPanel = new TabSecondPanel() { AdditionalDetails="Some Details for First Tab" };
TabContent firstTabContent = new TabContent() { TabFirstPanel = firstPanel, TabSecondPanel = secondPanel, ShowSecondPanel = false };
tabContentList.Add(firstTabContent);
SelectedTabItem = firstTabContent;
}
public void LoadSecondTab()
{
TabFirstPanel firstPanel = new TabFirstPanel() { Name = "John-2", Age = "31" };
TabSecondPanel secondPanel = new TabSecondPanel() { AdditionalDetails = "Some Details for second Tab" };
TabContent secondTabContent= new TabContent() { TabFirstPanel = firstPanel, TabSecondPanel = secondPanel, ShowSecondPanel=false };
tabContentList.Add(secondTabContent);
SelectedTabItem = secondTabContent;
}
public void LoadThirdTab()
{
TabFirstPanel firstPanel = new TabFirstPanel() { Name = "John-3", Age = "31" };
TabSecondPanel secondPanel = new TabSecondPanel() { AdditionalDetails = "Some Details for Third Tab" };
TabContent ThirdTabContent = new TabContent() { TabFirstPanel = firstPanel, TabSecondPanel = secondPanel, ShowSecondPanel = false };
tabContentList.Add(ThirdTabContent);
SelectedTabItem = ThirdTabContent;
}
public void ShowHideSecondPanelInTab()
{
TabContent currentTabContent = SelectedTabItem;
int currentIndex = tabContentList.IndexOf(SelectedTabItem);
if (currentTabContent.ShowSecondPanel)
{
currentTabContent.ShowSecondPanel = false;
}
else
{
currentTabContent.ShowSecondPanel = true;
}
TabContentList.RemoveAt(currentIndex);
TabContentList.Insert(currentIndex, currentTabContent);
OnPropertyChanged("TabContentList");
SelectedTabItem = currentTabContent;
}
private TabContent selectedTabItem = null;
private ObservableCollection<TabContent> tabContentList = null;
private ICommand loadTabCommand = null;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Code for TabContentTemplateSelector.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
namespace TabControlTestApp
{
class TabContentTemplateSelector : DataTemplateSelector
{
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null)
{
TabContent tabContent = (TabContent)item;
if (tabContent.ShowSecondPanel)
{
return element.FindResource("TabContentWithBothPanel") as DataTemplate;
}
else
{
return element.FindResource("TabContentWithFirstPanel") as DataTemplate;
}
}
else
{
return base.SelectTemplate(item, container);
}
}
}
}
Code for TabContent Data Object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TabControlTestApp
{
class TabFirstPanel
{
public string Name { get; set; }
public string Age { get; set; }
}
class TabSecondPanel
{
public string AdditionalDetails { get; set; }
}
class TabContent
{
public TabFirstPanel TabFirstPanel { get; set; }
public TabSecondPanel TabSecondPanel { get; set; }
public bool ShowSecondPanel { get; set; }
}
}
Code for LoadTabCommand Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace TabControlTestApp
{
class LoadTabCommand : ICommand
{
MainWindowViewModel mainWindowViewModel = null;
public LoadTabCommand(MainWindowViewModel mainWindowViewModel)
{
this.mainWindowViewModel = mainWindowViewModel;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
System.Windows.Controls.Button btn = (System.Windows.Controls.Button)parameter;
switch (btn.Name)
{
case "LoadTab1":
mainWindowViewModel.LoadFirstTab();
break;
case "LoadTab2":
mainWindowViewModel.LoadSecondTab();
break;
case "LoadTab3":
mainWindowViewModel.LoadThirdTab();
break;
case "ShowHideSecondPanelInTab":
mainWindowViewModel.ShowHideSecondPanelInTab();
break;
}
}
}
}
I took a look at your example. Thanks for posting code. Now I understand your issue completely. Before I suggested to change DynamicResource to StaticResource I thought you wanted to only look up once for your DataTemplate.
Now I see you wish to keep the instance of DataTemplate alive so TabControl doesn't destroy it when changing tabs.
Here is the solution:
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<local:TabContentTemplateSelector x:Key="tabContentTemplateSelector" />
<DataTemplate x:Key="TabitemDataTemplate">
<StackPanel Width="50" Height="50">
<TextBlock Text="{Binding TabFirstPanel.Name}"></TextBlock>
</StackPanel>
</DataTemplate>
<Grid x:Key="template1">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Name :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabFirstPanel.Name}"></TextBlock>
</Grid>
<Grid x:Key="template2">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Name :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabFirstPanel.Name}"></TextBlock>
</Grid>
<GridSplitter Grid.Row="0" Grid.Column="1"
VerticalAlignment="Stretch"
Width="5"
Height="Auto"
ResizeDirection="Columns"
ResizeBehavior="PreviousAndNext"/>
<Grid Grid.Row="0" Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Additional Detail :</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TabSecondPanel.AdditionalDetails}"></TextBlock>
</Grid>
</Grid>
<DataTemplate x:Key="TabContentWithFirstPanel">
<ContentPresenter Content="{StaticResource template1}"/>
</DataTemplate>
<DataTemplate x:Key="TabContentWithBothPanel">
<ContentPresenter Content="{StaticResource template2}"/>
</DataTemplate>
If you just copy past that you will do fine.
By the way, just as sidenote for you, destroying and building up DataTemplates is very important in wpf for releasing unmanaged memory.
I don't believe you may avoid this behavior, unless you use another control other than the TabControl.
The TabControl is a ItemControl-derived component: if its content is created via DataTemplate (as you done), the actual content is generated every time upon the current selection.
Another option is to fill the TabControl with direct content, and the inner controls should be preserved across the selection.
Have a look here:
http://msdn.microsoft.com/en-us/library/system.windows.controls.tabcontrol(v=vs.110).aspx
UPDATE: First off, I am not sure to have understand what you want, but here is a solution based on what I mean.
The fundamental trick is hosting directly the tab-contents, instead of creating via data-templating. That is:
<TabControl>
<TabItem Header="Tab1">
<TextBlock
Text="Page 1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</TabItem>
<TabItem Header="Tab2">
<CheckBox
Content="check me"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</TabItem>
<TabItem Header="Tab3">
<TextBlock
Text="Page 3"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</TabItem>
</TabControl>
The above snippet should "persist" the checkbox value across the tabs flipping.
But you need (or desire) some kind of templating, or a dynamic way to create the right content upon a certain data added to the tabcontrol.
The following trick should solve your problem:
<TabControl>
<TabItem
Header="Tab1"
>
<ContentControl
Content="{Binding Path=A}"
ContentTemplateSelector="{StaticResource sel}"
/>
</TabItem>
<TabItem
Header="Tab2"
>
<ContentControl
Content="{Binding Path=B}"
ContentTemplateSelector="{StaticResource sel}"
/>
</TabItem>
<TabItem
Header="Tab3"
>
<ContentControl
Content="{Binding Path=C}"
ContentTemplateSelector="{StaticResource sel}"
/>
</TabItem>
</TabControl>
This is using a trivial set of templates as follows:
<Window.Resources>
<local:MySelector x:Key="sel" />
<DataTemplate x:Key="dtplA">
<StackPanel Margin="30,30">
<TextBlock Text="A: " />
<TextBox />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="dtplB">
<StackPanel Margin="30,30">
<TextBlock Text="B: " />
<TextBox />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="dtplC">
<StackPanel Margin="30,30">
<TextBlock Text="C: " />
<TextBox />
</StackPanel>
</DataTemplate>
</Window.Resources>
And the behind-code is even more trivial:
public class VM
{
public A A { get; set; }
public B B { get; set; }
public C C { get; set; }
}
public class A { }
public class B { }
public class C { }
public class MySelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null)
{
return (DataTemplate)((FrameworkElement)container).FindResource("dtpl" + item.GetType().Name);
}
else
{
return base.SelectTemplate(item, container);
}
}
}
If you try this small example, the text typed into the textboxes will persist across the tabs flipping. That is, the templates will be called once only.
Let me know.
Related
I am trying to make a button in a viewmodel recognize that a radio button in another view model (a UserControl that is activated on the first viewmodel) has been selected, thus enabling the button in the first viewmodel.
I have a UserControl AlbumsDisplayViewModel within my base view model BaseViewModel.
In BaseView XAML There's a button (OpenAlbum) which is supposed to be enabled when a radio button on the AlbumsDisplayView is selected (see CanOpenAlbum).
BaseView XAML:
<Canvas x:Name="cnvsInputWrapper" Background="LightGray"
Grid.Column="4" Grid.Row="1" Grid.RowSpan="4"
Margin="5">
<Canvas.OpacityMask>
<VisualBrush Visual="{Binding ElementName=maskRoundEdges}" />
</Canvas.OpacityMask>
<DockPanel Margin="15, 25">
<ContentControl x:Name="ActiveItem" />
</DockPanel>
</Canvas>
<!-- Action Buttons section -->
<Grid Grid.Row="3" Grid.Column="1" Grid.RowSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="12" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="12" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="12" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="12" />
</Grid.RowDefinitions>
<Button Grid.Row="1" Grid.Column="1" x:Name="OpenAlbum"
IsEnabled="{Binding CanOpenAlbum}">
<StackPanel Orientation="Vertical">
<TextBlock>Open</TextBlock>
<TextBlock>Album</TextBlock>
</StackPanel>
</Button>
</Grid>
BaseViewModel C#:
public class BaseViewModel : Conductor<object>
{
private AlbumsDisplayViewModel m_vmAlbumsDisplay; // Initialized in another function.
public BaseViewModel()
{
}
public bool CanOpenAlbum() => (m_vmAlbumsDisplay != null) && (m_vmAlbumsDisplay.GetSelectedAlbum() != null);
public void OpenAlbum()
{
AlbumModel album = m_vmAlbumsDisplay.GetSelectedAlbum();
//ActivateItem(/*albumViewModel(album)*/);
}
}
AlbumsDisplayView XAML:
<ItemsControl x:Name="Albums" FlowDirection="LeftToRight"
Margin="10, 0">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type vms:AlbumViewModel}">
<StackPanel Orientation="Horizontal" Margin="0, 5">
<RadioButton GroupName="rdbtnAlbums"
IsChecked="{Binding IsSelected}" />
<!-- Album Details -->
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
AlbumsDisplayViewModel C#:
class AlbumsDisplayViewModel : Screen
{
private ObservableCollection<AlbumViewModel> m_albums;
public AlbumsDisplayViewModel()
{
}
public ObservableCollection<AlbumViewModel> Albums
{
get { return m_albums; }
set
{
m_albums = value;
NotifyOfPropertyChange(() => Albums);
}
}
public AlbumModel GetSelectedAlbum()
{
AlbumModel res = null;
foreach (var vmAlbum in Albums)
{
if (vmAlbum.IsSelected)
{
res = vmAlbum.Album;
break;
}
}
return res;
}
}
And last, AlbumViewModel C#:
class AlbumViewModel : Screen
{
private AlbumModel m_albumModel;
private bool m_isSelected;
public AlbumViewModel(AlbumModel albumModel)
{
m_albumModel = albumModel;
}
public AlbumModel Album
{
get { return m_albumModel; }
set
{
m_albumModel = value;
NotifyOfPropertyChange(() => Album);
}
}
public bool IsSelected
{
get { return m_isSelected; }
set
{
m_isSelected = value;
NotifyOfPropertyChange(() => IsSelected);
}
}
}
I expected that when IsSelected in AlbumViewModel is changed (when the user selects a radio button), the OpenAlbum button will be enabled, because CanOpenAlbum will return true, but I have realized that CanOpenAlbum wasn't even called for some reason. What do I need to do so CanOpenAlbum will be notified to be called whenever a radio button is selected?
After searching for an answer for a long time, I decided that it will be better to search for a better solution, instead of an answer. I've discovered that a ListBox element has a SelectedItem property, which eliminates the need for radio buttons.
Eventually, I replaced the ItemsControl with a ListBox, and I;m happy with the results.
AlbumDisplayView XAML (only this has changed):
<ScrollViewer x:Name="Scroller" Height="300"
FlowDirection="RightToLeft">
<ListBox x:Name="Albums" FlowDirection="LeftToRight"
Background="Transparent" Margin="10, 0"
BorderThickness="0" SelectedItem="{Binding SelectedAlbum}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type vms:AlbumViewModel}">
<StackPanel Orientation="Horizontal" Margin="0, 5">
<!-- Album Details -->
<StackPanel Orientation="Vertical">
<StackPanel Grid.Row="1" Grid.Column="1"
Orientation="Horizontal" Margin="12, 0">
<TextBlock Text="{Binding Album.Name}" />
<TextBlock Text=" - User#" />
<TextBlock Text="{Binding Album.OwnerID}" />
</StackPanel>
<TextBlock Text="{Binding Album.CreationDate}"
FontSize="12" Margin="12, 0" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</ScrollViewer>
I'm currently trying to bind my list to a list that is in another object from another list. But in the second listbox the Items just doesn't appear.
XAML
<Window x:Class="Managing_program.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:Managing_program"
mc:Ignorable="d"
Title="Dashboard" Height="416.701" Width="867.828">
<Grid>
<TabControl Margin="0,26,0,0">
<TabItem Header="Tables">
<Grid Background="White" Margin="0,0,-2,0">
<Button Content="Add" Margin="10,0,0,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75" Command="{Binding AddTableCommand}"/>
<Button Content="Remove" Margin="90,0,0,10" HorizontalAlignment="Left" Width="75" Height="20" VerticalAlignment="Bottom" Command="{Binding RemoveTableCommand}"/>
<GroupBox Header="Fields" HorizontalAlignment="Left" Margin="204,0,0,35" Width="192" FontWeight="Bold">
<Grid ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" BorderThickness="2" ItemsSource="{Binding SelectedTable.Fields}" SelectedItem="{Binding SelectedField}" Margin="0 4" FontWeight="Normal">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="test"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox Grid.Row="1" Margin="2" Text="{Binding FieldNameToAdd, Mode=TwoWay , UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</GroupBox>
<GroupBox Header="Tables" HorizontalAlignment="Left" Width="199" Margin="0,0,0,35" FontWeight="Bold">
<Grid ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<TextBox x:Name="tbAddTable" Grid.Row="1" Margin="2" Text="{Binding Path=TableNameToAdd, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<ListBox Grid.Row="0" ItemsSource="{Binding Tables}" SelectedItem="{Binding SelectedTable}" BorderThickness="2" Margin="0 4" FontWeight="Normal">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Name}"/>
<Label Content= "{Binding Fields.Count, StringFormat='Fields: {0}'}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</GroupBox>
<Button Content="Add" Margin="207,0,0,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75" Command="{Binding AddFieldCommand}"/>
<Button Content="Remove" Margin="287,0,0,10" HorizontalAlignment="Left" Width="75" Height="20" VerticalAlignment="Bottom" Command="{Binding RemoveFieldCommand}"/>
<GroupBox Header="Field properties" Margin="401,0,10,35" FontWeight="Bold">
<Grid Margin="10,10,-2,5" ShowGridLines="True" DataContext="{Binding SelectedField}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="28"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Label:"/>
<Label Grid.Row="2" Grid.Column="0" Content="Type:"/>
<Label Grid.Row="3" Grid.Column="0" Content="Reference table:"/>
<Label Grid.Row="4" Grid.Column="0" Content="Visible:"/>
<Label Grid.Row="0" Grid.Column="1" Content="{Binding Name}" Margin="10,0,0,0"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Label}" Margin="5,2,0,2"/>
<ComboBox Grid.Column="1" Margin="5,5,0,5" Grid.Row="2" BorderBrush="White" RenderTransformOrigin="1.029,0.62">
</ComboBox>
<ComboBox Grid.Column="1" Margin="5,5,-0,121" Grid.Row="3" BorderBrush="White" RenderTransformOrigin="1.029,0.62">
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</TabItem>
<TabItem Header="TabItem">
</TabItem>
</TabControl>
</Grid>
</Window>
MainViewModel:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace Managing_program.model
{
class MainWindowViewModel: ViewModelBase
{
public MainWindowViewModel()
{
// registering all commands
Tables = new ObservableCollection<Table>();
AddTableCommand = new DelegateCommand(ExecuteAddTableCommand, CanExecuteAddTableCommand);
RemoveTableCommand = new DelegateCommand(ExecuteRemoveTableCommand, CanExecuteRemoveTableCommand);
AddFieldCommand = new DelegateCommand(ExecuteAddFieldCommand, CanExecuteAddFieldCommand);
}
String _fieldNameToAdd = String.Empty;
public String FieldNameToAdd {
get { return _fieldNameToAdd; }
set {
_fieldNameToAdd = value;
OnPropertyChanged("FieldNameToAdd");
}
}
String _tableNameToAdd = string.Empty;
public String TableNameToAdd {
get {return _tableNameToAdd;}
set {
_tableNameToAdd = value;
OnPropertyChanged("TableNameToAdd");
}
}
#region allCommands:
// Add Table Command
public ICommand AddTableCommand { get; set; }
private void ExecuteAddTableCommand(object parameter)
{
Tables.Add(new Table(TableNameToAdd));
TableNameToAdd = String.Empty;
}
private bool CanExecuteAddTableCommand(object paramater)
{
if (TableNameToAdd.Length < 1)
return false;
if (TableNameToAdd.Contains(" "))
return false;
foreach (Table table in Tables)
{
if (table.Name.ToLower() == TableNameToAdd)
return false;
}
return true;
}
// Remove Table Command
public ICommand RemoveTableCommand { get; set; }
private void ExecuteRemoveTableCommand(object paramater){
Tables.Remove(SelectedTable);
}
private bool CanExecuteRemoveTableCommand(object parameter)
{
return SelectedTable != null;
}
// AddFieldCommand
public ICommand AddFieldCommand { get; set; }
private void ExecuteAddFieldCommand(object parameter)
{
SelectedTable.Fields.Add(new Field("test"));
}
private bool CanExecuteAddFieldCommand(object parameter)
{
if (SelectedTable == null)
return false;
if (FieldNameToAdd.Length < 1)
return false;
if (FieldNameToAdd.Contains(" "))
return false;
foreach (Field field in SelectedTable.Fields)
{
if (field.Name.ToLower() == FieldNameToAdd.ToLower())
return false;
}
return true;
}
#endregion
public ObservableCollection<Table> Tables { get; private set; }
public Table SelectedTable { get; set; }
public Field SelectedField { get; set; }
}
}
Table class:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Managing_program.model
{
class Table
{
public Table(String name)
{
Name = name;
Fields = new ObservableCollection<Field>();
}
public String Name { get; private set; }
public ObservableCollection<Field> Fields { get; private set; }
}
}
The second listbox just doesn't update. Please help!
Okay I found the problem! I had to implement OnPropertyChanged() in the SelectedTable property. It start to work right away after that!
I have a WPF application and just embarked in learning MVVM pattern.
My goal is that in my application the main window has a button. When this button is clicked, another window (or user control) will appear on top of the main window.
This is the code of MainWindow.xaml
<Window x:Class="SmartPole1080.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:utilities="clr-namespace:SoltaLabs.Avalon.Core.Utilities;assembly=SoltaLabs.Avalon.Core"
xmlns:userControls="clr-namespace:SoltaLabs.Avalon.View.Core.UserControls;assembly=SoltaLabs.Avalon.View.Core"
xmlns:controls="clr-namespace:WpfKb.Controls;assembly=SmartPole.WpfKb"
xmlns:wpf="clr-namespace:WebEye.Controls.Wpf;assembly=WebEye.Controls.Wpf.WebCameraControl"
xmlns:view="clr-namespace:SmartPole.View;assembly=SmartPole.View"
xmlns:view1="clr-namespace:SmartPole1080.View"
xmlns:behaviors="clr-namespace:SoltaLabs.Avalon.Core.Behaviors;assembly=SoltaLabs.Avalon.Core"
Title="Smart Pole"
WindowStartupLocation="CenterScreen"
Name="mainWindow"
behaviors:IdleBehavior.IsAutoReset="True" WindowState="Maximized" WindowStyle="None">
<Canvas Background="DarkGray">
<!--Main Grid-->
<Grid Width="1080" Height="1920" Background="White" Name="MainGrid"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<StackPanel Background="Black">
<Grid Background="#253341">
<Grid.RowDefinitions>
<RowDefinition Height="5"/>
<RowDefinition Height="*"/>
<RowDefinition Height="5"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="264"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Grid.Column="1">
<Button Tag="{StaticResource EmergencyImg}" Name="EmergencyButton"
Command="{Binding ShowEmergencyPanel}">
<Image Source="{StaticResource EmergencyImg}" />
</Button>
</Grid>
<!--Emergency Window Dialog-->
<Grid Name="EmergencyPanel">
<view1:EmergencyInfo x:Name="EmergencyInfoPanel"/>
</Grid>
</Grid>
</StackPanel>
</Grid>
<!--Main Grid-->
</Canvas>
This is the other window (user control - EmergencyInfo.xaml)
<UserControl x:Class="SmartPole1080.View.EmergencyInfo"
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:SmartPole1080.View"
mc:Ignorable="d"
d:DesignHeight="1920" d:DesignWidth="1050"
x:Name="EmergencyInfoPanel">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" BorderBrush="White" Background="White">
<Button Background="White" BorderThickness="0" FontWeight="Bold" Foreground="Red"
HorizontalAlignment="Right" FontSize="25" Margin="0,0,15,0"
Command="{Binding HideEmergencyPanel}">
close X
</Button>
</Border>
<Image Grid.Row="1" Source="{StaticResource EdenParkInfoImg}" HorizontalAlignment="Left" />
</Grid>
I want to implement this behavior using an MVVM pattern. I have set the binding ShowEmergencyPanel in button EmergencyButton to show EmergencyInfo when this button is click.
Any help is greatly appreciated.
Why dont you make navigation, something like this. Make section for conetent that will be injected, and whatever type of object you are expecting put it in Windows.Resources in DataTemplate.
In main windo xaml
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type home:HomeViewModel}">
<home:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type other:OtherViewModel}">
<other:OtherView />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid x:Name="Navigation">
<StackPanel Orientation="Horizontal">
<Button x:Name="HomeView"
Content="Home"
Margin="5"
Command="{Binding NavigationCommand}"
CommandParameter="home" />
<Button x:Name="Menu"
Content="OtherView"
Margin="5"
Command="{Binding NavigationCommand}"
CommandParameter="Other" />
</StackPanel>
</Grid>
<Grid x:Name="MainContent"
Grid.Row="1">
<ContentControl Content="{Binding CurrentViewModel}" />
</Grid>
</Grid>
MainWindowViewModel can look something like this.
public class MainWindowViewModel : INotifyPropertyChanged
{
private OtherViewModel otherVM;
private HomeViewModel homeVM;
public DelegateCommand<string> NavigationCommand { get; private set; }
public MainWindowViewModel()
{
otherVM = new OtherViewModel();
homeVM = new HomeViewModel();
// Setting default: homeViewModela.
CurrentViewModel = homeVM;
NavigationCommand = new DelegateCommand<string>(OnNavigate);
}
private void OnNavigate(string navPath)
{
switch (navPath)
{
case "other":
CurrentViewModel = otherVM;
break;
case "home":
CurrentViewModel = homeVM;
break;
}
}
private object _currentViewModel;
public object CurrentViewModel
{
get { return _currentViewModel; }
set
{
if (_currentViewModel != value)
{
_currentViewModel = value;
OnPropertyChanged();
}
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged(this, new propertyChangedEventArgs(propertyName));
}
#endregion
}
Where DelegateCommand you can make yours,check how to make RelayCommand(and generic one) or use PRISM that have it's own DelegateCommand. But if you want to use PRISM, it allready has navigation to regions, that can solve many problems. Check videos from Brian Lagunas.
EDIT:
This is to show/hide grid. In your mainWindow where you set that EmergencyInfo u can show/hide that grid this way.
in your MainViewViewModel make a bool property IsVisible
private bool _isVisible;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
OnPropertyChanged();
}
}
in your MainView.Resources set key to BooleanToVisibilityConverter
something like:
<BooleanToVisibilityConverter x:Key="Show"/>
and your grid that you want to show/hide set visibility:
<Grid x:Name="SomeGridName"
Grid.Row="1"
Grid.Colum="1"
Visibility="{Binding IsVisible,Converter={StaticResource Show}}">
And finally set that IsVisible property to some ToggleButton, just to switch between true/false
<ToggleButton IsChecked="{Binding IsVisible}"
Content="ShowGrid" />
This way, you show/hide that grid part based on IsVisible, and you control that visibility onClick. Hope that helps.
Inside your Window xaml:
<ContentPresenter Content="{Binding Control}"></ContentPresenter>
In this way, your ViewModel must contain a Control property.
Add your ViewModel to DataContext of Window.
(For example in window constructor, this.Datacontext = new ViewModel();)
Or another way with interfaces:
public interface IWindowView
{
IUserControlKeeper ViewModel { get; set; }
}
public interface IUserControlKeeper
{
UserControl Control { get; set; }
}
public partial class YourWindow : IViewWindow
{
public YourWindow()
{
InitializeComponent();
}
public IUserControlKeeper ViewModel
{
get
{
return (IUserControlKeeper)DataContext;
}
set
{
DataContext = value;
}
}
}
(In this way, initialize your window where you want to use. Service?)
private IViewWindow _window;
private IViewWindow Window //or public...
{
get{
if(_window==null)
{
_window = new YourWindow();
_window.ViewModel = new YourViewModel();
}
return _window;
}
}
Open your window with one of your UserControls:
void ShowWindowWithControl(object ControlView, INotifyPropertyChanged ControlViewModel, bool ShowAsDialog)
{
if(ControlView is UserControl)
{ //with interface: Window.ViewModel.Control = ...
(Window.DataContext as YourViewModel).Control = (UserControl)ControlView;
if (ControlViewModel != null)
(Window.DataContext as YourViewModel).Control.DataContext = ControlViewModel;
if (ShowAsDialog) //with interface use cast to call the show...
Window.ShowDialog();
else
Window.Show();
}
}
What you can do is, place the Emergency usercontrol inside MainGrid and control its visibility through Model property.
<Canvas Background="DarkGray">
<!--Main Grid-->
<Grid Width="1080" Height="1920" Background="White" Name="MainGrid"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<StackPanel Background="Black">
<Grid Background="#253341">
<Grid.RowDefinitions>
<RowDefinition Height="5"/>
<RowDefinition Height="*"/>
<RowDefinition Height="5"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="264"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Grid.Column="1">
<Button Tag="{StaticResource EmergencyImg}" Name="EmergencyButton"
Command="{Binding ShowEmergencyPanel}">
<Image Source="{StaticResource EmergencyImg}" />
</Button>
</Grid>
</Grid>
</StackPanel>
<Grid Name="EmergencyPanel">
<view1:EmergencyInfo x:Name="EmergencyInfoPanel" Visibility={Binding IsEmergencyPanelVisible,Converter={StaticResource BoolToVisibilityConverter}} DataContext={Binding} />
</Grid>
</Grid>
<!--Main Grid-->
</Canvas>
By setting proper background to Grid that holding usercontrol, you can achieve modal window like effect.
And you need to have IsEmergencyPanelVisible(default value is false) is your Model, and this property should be changed to true on your button click command.
Note : I guess you are familiar with converters, so i included Converters in my solution.
I have a Grid control that is proportioned using star e.g.
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="100*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>
However putting a long TextBlock in the grid that overflows causes the proportions to be upset. e.g.
<TextBlock Text="Foo" Grid.Column="0" />
<TextBlock Text="Some long text here which overflows" Grid.Column="1" />
<TextBlock Text="Foo" Grid.Column="2" />
This causes the central column to be more than double the other two. How do I maintain the specified proportions? Is it possible to clip the content?
I have set TextTrimming="CharacterEllipsis" on the TextBlocks but no luck.
Edit
Crucially it seems, the Grid is inside a DataTemplate, paste the following to observe the behaviour,
<!-- FallbackValue is just a quick hack to get some rows to show at design-time -->
<ListBox ItemsSource="{Binding Foo, FallbackValue=1234}"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="100*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Foo" Grid.Column="0" />
<TextBlock Text="Some long text here which overflows" TextTrimming="CharacterEllipsis" Grid.Column="1" />
<TextBlock Text="Foo" Grid.Column="2" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The reason why this is important is that I have another Grid as a sibling of the ListBox which displays the 'headers' for the columns shown in the ListBox as follows,
<Grid>
... Headers and column definitions here
</Grid>
<ListBox ...>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
... Matching column definitions here
</Grid>
</DateTemplate>
</ListBox.ItemTemplate>
</ListBox>
and so it is important that the columns match up.
I have tried to bind the ColumnDefinitions inside the DataTemplate to the external Grid ColumnDefinitions but I cannot get easily a binding reference to it.
This is one of the most annoying problems with WPF. Since the available space yielded to the templated grid is infinite, the actual content will take as much space as it wants.
The simplest way is to fix a certain width to the Grid, but that solves only the situations where there's no resizing.
Whereas you want to stretch the ListBox size (width, in the specific), unfortunately I guess that there's no any better solution other than a custom converter.
Here is my solution:
<Window.Resources>
<local:MyConv x:Key="cv1" />
</Window.Resources>
<Grid>
<ListBox
ItemsSource="{Binding Foo, FallbackValue=1234}"
HorizontalContentAlignment="Stretch"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}, Converter={StaticResource cv1}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="100*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Foo" Grid.Column="0" />
<TextBlock Text="Some long text here which overflows" TextTrimming="CharacterEllipsis" Grid.Column="1" />
<TextBlock Text="Foo" Grid.Column="2" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
And the converter:
class MyConv : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture
)
{
return (double)value - 30.0;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Even though this is an old post I'm adding my findings as they might be relevant for other people reading this post.
I had a similar issue (my * columns weren't dividing the width evenly as expected anymore, they were just sizing based on the content).
The root cause here was that I had a ListView with an ItemsSource linked to a List. The ListView in WPF contains a ScrollViewer and a ScrollViewer doesn't have a fixed width.
Without a fixed width a Grid can't properly determine what width to give to a * column and switches to a different sizing method.
Solution
I now use an ItemsControl which doesn't contain a ScrollViewer and thus the Width is known allowing the Grid to properly size it's columns.
For more details on how exactly the Grid handles it's sizing I suggest you decompile the Grid class and have a look at the following method:
protected override Size MeasureOverride(Size constraint)
This is my MainWindow.xaml from my test application (comment out the ListView to see the difference in behaviour):
<Window x:Class="WPFSO.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfso="clr-namespace:WPFSO"
Title="MainWindow" Height="150" Width="525">
<Window.DataContext>
<wpfso:SharedSizeScopeViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type wpfso:TestViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" x:Name="SecondColumn" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" x:Name="FourthColumn" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name}" />
<TextBlock Grid.Column="1" Background="LightGray" Text="{Binding Name2}"/>
<TextBlock Grid.Column="2" Text="{Binding Name3}"/>
<TextBlock Grid.Column="3" Background="Orange" Text="{Binding Name4}"/>
<!--<TextBlock Grid.Column="1" Background="Blue" HorizontalAlignment="Stretch" />
<TextBlock Grid.Column="3" Background="Orange" HorizontalAlignment="Stretch" />-->
</Grid>
</DataTemplate>
<DataTemplate x:Key="MainDataTemplate" DataType="wpfso:SharedSizeScopeViewModel" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Grid.ColumnSpan="4" HorizontalAlignment="Left" FlowDirection="RightToLeft" Margin="0,0,0,25">
<TextBlock FlowDirection="LeftToRight" Text="Show differences" Style="{StaticResource LabelStyle}" />
</CheckBox>
<TextBlock Grid.Row="1" Grid.Column="0" Text="PropertyName" Style="{StaticResource LabelStyle}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="Previous value" Style="{StaticResource LabelStyle}" />
<TextBlock Grid.Row="1" Grid.Column="3" Text="Current value" Style="{StaticResource LabelStyle}" />
<ListView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4" ItemsSource="{Binding Entries}" HorizontalAlignment="Stretch" Margin="0" HorizontalContentAlignment="Stretch"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Name="RootGrid">
<ItemsControl ItemsSource="{Binding Entries}" />
<!--<ListView ItemsSource="{Binding Entries}" />-->
</Grid>
</Window>
The ViewModels used during this test:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WPFSO
{
public class SharedSizeScopeViewModel : INotifyPropertyChanged
{
public SharedSizeScopeViewModel()
{
var testEntries = new ObservableCollection<TestViewModel>();
testEntries.Add(new TestViewModel
{
Name = "Test",
Name2 = "Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong test",
Name3 = "Short test",
Name4 = "Nothing"
});
Entries = testEntries;
}
private ObservableCollection<TestViewModel> _entries;
public ObservableCollection<TestViewModel> Entries
{
get { return _entries; }
set
{
_entries = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
First viewmodel
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WPFSO
{
public class SharedSizeScopeViewModel : INotifyPropertyChanged
{
public SharedSizeScopeViewModel()
{
var testEntries = new ObservableCollection<TestViewModel>();
testEntries.Add(new TestViewModel
{
Name = "Test",
Name2 = "Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong test",
Name3 = "Short test",
Name4 = "Nothing"
});
Entries = testEntries;
}
private ObservableCollection<TestViewModel> _entries;
public ObservableCollection<TestViewModel> Entries
{
get { return _entries; }
set
{
_entries = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Second viewmodel
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WPFSO
{
public class TestViewModel : INotifyPropertyChanged
{
private string _name;
private string _name2;
private string _name3;
private string _name4;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged();
}
}
public string Name2
{
get { return _name2; }
set
{
_name2 = value;
OnPropertyChanged();
}
}
public string Name3
{
get { return _name3; }
set
{
_name3 = value;
OnPropertyChanged();
}
}
public string Name4
{
get { return _name4; }
set
{
_name4 = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Set
TextTrimming="CharacterEllipsis"
on the TextBlock.
It works for me. As you have defined the middle column should be twice the size of the other.
I find myself in a similar situation but TextTrimming isn't available.
Ends up binding child Width to Grid.ActualWidth with a Converter converts the ratio into absolute width.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="100*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>
<Grid.Resources>
<local:PartConv x:Key="partConv"/>
<sys:Double x:Key="r0">0.25</sys:Double>
<sys:Double x:Key="r1">0.5</sys:Double>
<sys:Double x:Key="r2">0.25</sys:Double>
</Grid.Resources>
<TextBlock Text="Foo" Grid.Column="0"
Width="{Binding ActualWidth,
RelativeSource={RelativeSource AncestorType=Grid}},
Converter={StaticResource partConv},
ConverterParameter={StaticResource r0}}"/>
<TextBlock Text="Some long text here which overflows" Grid.Column="1"
Width="{Binding ActualWidth,
RelativeSource={RelativeSource AncestorType=Grid}},
Converter={StaticResource partConv},
ConverterParameter={StaticResource r1}}"/>
<TextBlock Text="Foo" Grid.Column="2"
Width="{Binding ActualWidth,
RelativeSource={RelativeSource AncestorType=Grid}},
Converter={StaticResource partConv},
ConverterParameter={StaticResource r2}}"/>
</Grid>
[ValueConversion(typeof(double), typeof(double))]
public class PartConv : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> ((double)value) * ((double)parameter);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> ((double)value) / ((double)parameter);
}
I have a listbox in which I render data using multiple datatemplates, and I use a datatemplate selector to route data to the appropriate template.
Each template has it's own layout using a grid. The first column of every grid inside the template is a textblock and I want them aligned to left. The next item is another textblock which should be aligned towards the maximum width of the first textblock (something similar to a data entry form). I'm using Grid.IsSharedSizeScope for this, but not able to achieve this. Below is my code:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<DataTemplate x:Key="DefaultTemplate">
<Border BorderThickness="1" CornerRadius="3" BorderBrush="LightGray">
<TextBlock Text="{Binding Name}"></TextBlock>
</Border>
</DataTemplate>
<DataTemplate x:Key="ShortFieldTemplate">
<Grid Grid.IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="A"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="Age:" Grid.Column="0"></TextBlock>
<TextBlock Text="{Binding Age}" Grid.Column="1"></TextBlock>
</Grid>
</DataTemplate>
<DataTemplate x:Key="LongFieldTemplate">
<Grid Grid.IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="A"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="This should be the name:" Grid.Column="0"></TextBlock>
<TextBlock Text="{Binding Name}" Grid.Column="1"></TextBlock>
</Grid>
</DataTemplate>
<GridSplitterTextTrim:MyFirstTemplateSelector x:Key="MyFirstTemplateSelector"
DefaultDataTemplate="{StaticResource DefaultTemplate}"
ShortFieldDataTemplate="{StaticResource ShortFieldTemplate}"
LongFieldDataTemplate="{StaticResource LongFieldTemplate}"
/>
</Page.Resources>
<Grid x:Name="LayoutRoot" Grid.IsSharedSizeScope="True">
<Grid Grid.Column="2" Background="Green" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ListBox ItemsSource="{Binding Items}" Grid.Row="0" Grid.Column="0" x:Name="listbox" ItemTemplateSelector="{StaticResource MyFirstTemplateSelector}">
</ListBox>
</Grid>
</Grid>
</Page>
..and my object model
public class ShortField : INotifyPropertyChanged
{
private string _name;
public string Age
{
get { return _name; }
set
{
_name = value;
InvokePropertyChanged(new PropertyChangedEventArgs("Age"));
}
}
private string _currentValue;
public string CurrentValue
{
get { return _currentValue; }
set
{
_currentValue = value;
InvokePropertyChanged(new PropertyChangedEventArgs("CurrentValue"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
public static List<ShortField> GetShortFields()
{
return new List<ShortField>()
{
new ShortField() {Age = "10"},
new ShortField() {Age = "21"},
};
}
}
How do I get this alignment right? I thought Grid.IsSharedScope should do the trick. Is that correct or is there any other way?
Thanks in advance,
-Mike
try to set
<ListBox Grid.IsSharedSizeScope="True"