DataTemplate only shows Canvas for the last record - wpf

I'm using the following DataTemplate
<DataTemplate x:Key="platform_resources">
<StackPanel Orientation="Horizontal">
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<ContentControl DataContext="{Binding}" Focusable="False" Content="{DynamicResource appbar_server}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=workload_count}"/>
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<Viewbox Width="30" Height="30" ToolTip="Logical Network Count" Stretch="Uniform">
<ContentControl Focusable="False" Content="{DynamicResource appbar_network_server_connecting}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=vlan_count}"/>
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<ContentControl Focusable="False" Content="{DynamicResource appbar_network}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=networkdomain_count}"/>
</StackPanel>
</DataTemplate>
The template displays all the relevant data with separators but only shows the images on the last record. It's leaves spaces where the images are supposed to be, but no images.

Make sure you add x:Shared="False" property to your resources.
Example:
<Canvas x:Key="appbar_server" x:Shared="False">
<!-- ... -->
</Canvas>

This happens because you probably defined some Images (e.g appbar_server) in your resources and trying to display them in multiple items. But Image is a Visual and in WPF each Visual can only have one parent. So when your items are being generated, each item steals the Image from the previous one until the last item finally gets it.
Solution:
Unlike Image, BitmapImage is not a Visual and thus can be set multiple times as the source of different items. So instead of defining Images in your Resources, define BitmapImages:
<Window.Resources>
<BitmapImage x:Key="appbar_server" UriSource="C:\...\appbar_server.png"/>
....
And then instead of ContentControls create Image instances in your DataTemplate to present them:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<Image Focusable="False" Source="{DynamicResource appbar_server}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=workload_count}"/>
...
*Update:
The image is captured in a canvas which seems to be needing some
special wrapper to make this work.
In that case, you should define a DataTemplate for each Canvas like this:
<Window.Resources>
<DataTemplate x:Key="appbar_3d_3ds">
<Canvas Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
<Path Width="32" Height="40" Canvas.Left="23" Canvas.Top="18" Stretch="Fill" Fill="Black" Data="F1 M 27,18L 23,26L 33,30L 24,38L 33,46L 23,50L 27,58L 45,58L 55,38L 45,18L 27,18 Z "/>
</Canvas>
</DataTemplate>
....
And then create ContentPresenter Instances in your ItemTemplate with their ContentTemplate set to your pre-defined data templates (e.g. appbar_3d_3ds).
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<ContentPresenter ContentTemplate="{DynamicResource appbar_3d_3ds}"/>
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=workload_count}"/>
....

Related

Centre a label within my user control that is positioned within a canvas WPF

Attempting to centre my label in my User Control to my 'signal' I have drawn within my canvas.
This is what my signals currently look like, with their names below the signal. As you can see, due to the variation in name length, some are off centred.
My user control XAML code:
<UserControl x:Name="LeftUserControl"
d:DesignHeight="50" d:DesignWidth="50" RenderTransformOrigin="0.84,0.5">
<Viewbox Stretch="Uniform" Width="10" Height="10">
<Canvas Height="150" Width="150">
<Label Content="{Binding SignalName, ElementName=LeftUserControl}" Foreground="Black" Canvas.Top="108" FontSize="15" Canvas.Left="85"></Label>
<Line X1="130" X2="130" Y1="105" Y2="84" Stroke="Black" StrokeThickness="5" StrokeStartLineCap="Round" ></Line>
<Line X1="130" X2="100" Y1="105" Y2="105" Stroke="Black" StrokeThickness="5"></Line>
<Ellipse Fill="Red" Width="25" Height="25" Canvas.Left="85" Canvas.Top="92"/>
</Canvas>
</Viewbox>
</UserControl>
My main window where I'm using my user control:
<DataTemplate DataType="{x:Type viewModel:SignalLeftViewModel}">
<Canvas>
<userControls:SignalLeftControl SignalName="{Binding Name}" Canvas.Top="{Binding SignalCoords.Y, Converter={StaticResource ScaleYCoordConverter},ConverterParameter=leftSignal}" Canvas.Left="{Binding SignalCoords.X, Converter={StaticResource ScaleXCoordConverter}, ConverterParameter=leftSignal}">
<userControls:SignalLeftControl.RenderTransform>
<RotateTransform Angle="{Binding Angle}"/>
</userControls:SignalLeftControl.RenderTransform>
</userControls:SignalLeftControl>
</Canvas>
</DataTemplate>
I'm wondering what the easiest way is to centre my label within my user control, so that all the names are aligned properly. Thanks in advance.

Imagebrush is stretching one instance of an image but not another

One of the stranger occurrences I've come across, I have a set of repeatbuttons that use a certain image as a background. Despite the buttons being identical, one is displayed differently. Fully reproducible sample below, along with a number of variations each with different results.
Link to icons:
https://github.com/driftyco/ionicons/blob/master/png/512/plus.png
https://github.com/driftyco/ionicons/blob/master/png/512/minus.png
<Grid Margin="0,0,0,0" >
<StackPanel Orientation="Horizontal" Height="32">
<StackPanel.Resources>
<ImageBrush x:Key="plusImage" ImageSource="/Resources/plus.png" />
<ImageBrush x:Key="minusImage" ImageSource="/Resources/minus.png" />
</StackPanel.Resources>
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource minusImage}}"/>
<TextBlock Margin="5,0,5,0"
VerticalAlignment="Top"
FontWeight="Bold"
Text="X" />
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource plusImage}}"/>
<Separator Margin="5,0,5,0" Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource minusImage}}"/>
<TextBlock Margin="5,0,5,0"
VerticalAlignment="Top"
FontWeight="Bold"
Text="Y" />
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource plusImage}}"/>
<Separator Margin="5,0,5,0" Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource minusImage}}"/>
<TextBlock Margin="5,0,5,0"
VerticalAlignment="Top"
FontWeight="Bold"
Text="Z" />
<RepeatButton Width="20"
Height="20"
Background="{Binding Source={StaticResource plusImage}}"/>
</StackPanel>
</Grid>
I'm creating a control to control the x, y, z positions of a point. As you can see in the image above, only one of the plus icons appears to be stretched.
Variations:
If I remove Z and the icons associated with it, the last plus icon for Y is NOT stretched
Removing the fontweight from Z makes the plus icon appear normal (not stretched)
What would cause an imagebrush to stretch an image like this?
You could set the UseLayoutRounding property on the RepeatButtons:
<RepeatButton Width="20" Height="20" UseLayoutRounding="True"
Background="{Binding Source={StaticResource plusImage}}"/>

WPF Modal Window Transparency

I have created a modal WPF window that looks as follows:
Here is the code for the window:
<Window x:Class="Dionysus.Core.Controls.ModalWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ModalWindow" AllowsTransparency="True" Background="Transparent" WindowStyle="None">
<Grid Name="MainGrid">
<Rectangle Fill="Gray" Opacity="0.7" />
</Grid>
The "ErrorControl" is then added as follows:
MainGrid.Children.Add(uc);
The problem is as soon as I expand the stack trace, the controls transparency also changes:
I am assuming this has something to do with the ScrollViewer that uses the incorrect transparency, ie of the Rectangle instead of the containing Window.
I have also set the Opacity of the UserControl which owns the ScrollViewer to 1 and then binded the Opacity:
<ScrollViewer Background="WhiteSmoke" Opacity="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=Opacity}">
Can anyone help me?
--
UPDATE
Here is the code for the UserControl that is inserted into the Window
<Grid x:Name="LayoutRootx" Background="WhiteSmoke">
<StackPanel VerticalAlignment="Stretch">
<TextBlock TextWrapping="Wrap" Margin="5" Text="An error has occured:" Foreground="Black" FontSize="15" FontWeight="Medium"/>
<TextBlock TextWrapping="Wrap" Margin="5,10,5,5" Text="{Binding Error}"/>
<odc:OdcExpander Header="Stack Trace" Margin="5" IsExpanded="False" Background="WhiteSmoke">
<TextBox Text="{Binding StackTrace}" TextWrapping="Wrap" Margin="5,10,5,5" IsReadOnly="True" MaxHeight="370"/>
</odc:OdcExpander>
<odc:OdcExpander Header="Comment" Margin="5" IsExpanded="False">
<TextBox Text="{Binding Comment}" TextWrapping="Wrap" Margin="5,10,5,5" MaxHeight="370" Name="txtComment"/>
</odc:OdcExpander>
<StackPanel Margin="5,10,5,5" Orientation="Horizontal" HorizontalAlignment="Left">
<Button Style="{StaticResource DionysusButton}" Width="100" Height="23" IsDefault="True" Name="btnSendError">
<StackPanel Orientation="Horizontal">
<Image Source="/Dionysus.Shell;component/Images/camera-icon.png" Margin="0,0,5,0">
</Image>
<TextBlock Text="Send to IT" VerticalAlignment="Center"/>
<core:DionysusTriggerAction Height="0" Width="0" TargetControl="{Binding ElementName=btnSendError}" MethodName="SendError"></core:DionysusTriggerAction>
</StackPanel>
</Button>
<Button Style="{StaticResource DionysusButton}" Width="100" Height="23" Name="btnExit" Margin="10,0,0,0" IsCancel="True">
<StackPanel Orientation="Horizontal">
<Image Source="/Dionysus.Shell;component/Images/DeleteRed.png" Margin="0,0,5,0">
</Image>
<TextBlock Text="Close" VerticalAlignment="Center"/>
</StackPanel>
</Button>
<core:DionysusTriggerAction Height="0" Name="triggerAction2" Width="0" TargetControl="{Binding ElementName=btnExit}" MethodName="Exit"></core:DionysusTriggerAction>
</StackPanel>
</StackPanel>
</Grid>
If your window has a fixed size and cannot be resized, you can use the following trick:
<Grid>
<Border BorderThickness="100" BorderBrush="Gray" Opacity="0.7">
<Grid Background="White" Grid.Column="1" Grid.Row="1" x:Name="contentPlaceHolder">
<TextBlock Text="HELLO WORLD" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Border>
</Grid>
However, it is unlikely that your Window will always have the same size, so to make it more dynamic, you could change the layout of the Window as follows:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="YourDesiredSize"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="YourDesiredSize"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Rectangle Fill="Gray" Opacity="0.7" Grid.Row="0" Grid.ColumnSpan="3"/>
<Rectangle Fill="Gray" Opacity="0.7" Grid.Row="2" Grid.ColumnSpan="3"/>
<Rectangle Fill="Gray" Opacity="0.7" Grid.Row="1" Grid.Column="0"/>
<Rectangle Fill="Gray" Opacity="0.7" Grid.Row="1" Grid.Column="2"/>
<Grid Grid.Column="1" Grid.Row="1" Background="White" x:Name="contentPlaceHolder">
<TextBlock Text="HELLO WORLD" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Grid>
The result of this window placed on top of another looks more or less like this:
and then instead of adding to the MainGrid, add the UserControl to the contentPlaceHolder or however you want to call it:
contentPlaceHolder.Children.Add(uc);
Okay so I found a solution that works for me, I'm sure it's not the best but it might help someone having the same problem as I did.
The problem was that controls within my UserControl that I added to my Window were transparent, although I could not figure out the reason, I found a simple workaround.
By changing the OpacityMask property of the UserControl to whatever the required Background colour is, even if the controls opacity changes, it will be masked with the Brush that you supply.
uc.OpacityMask = Brushes.WhiteSmoke;
Hope it helps someone!

WPF unexpected control unload

I'm developing a WPF application using MVVM. Inside a Window, I have a control that inherits from UserControl, lets call it DetailView.
DetailView is binded to a property in the VM (CurrentDetail) that can be of different types, UserDetail, AccountDetail, CalendarDetail, etc. All inherit from the same class
I have a "ThumbnailBar" in which I can navigate between different detail instances that have been already opened, imagine AccountDetail1, AccountDetail2, etc.
This navigation is handled updating CurrentDetail in the VM and with the OnPropertyChanged event
The problem comes when I switch from one type (AccontDetail3 for example) to another different type (UserDetail6). I have noticed it calls the "Unloaded" event of the control I'm leaving and the control I'm going to is Initialized, both things don't happen when I navigate through instance of the same type
This causes me some problems, like in calendar where I have a telerik RadScheduler that wont keep the date I had navigated to and reload with the today date.
I know and I have already tested, I could save the variable SelectecTimeSlot and keep reloading it, but that would be just a patch
EDIT - some code:
Here is MainView.xaml where I call CurrentDetailsWorkSpace
<Border x:Name="BorderExteriorContent" BorderBrush="Transparent" BorderThickness="0"
Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2">
<ContentControl
x:Name="DetalleContenidoWrkSpc"
Background="Red"
Height="{Binding ElementName=BorderExteriorContent,Path=ActualHeight}"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Content="{Binding CurrentDetailsWorkSpace}"
VerticalAlignment="Top" Panel.ZIndex="1" />
</Border>
And here is CalendarView (one of the views That unloads) and yes I'm using DataTemplates
<base:BaseUCView
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:base="clr-namespace:MRWTINT.HGC.Win.Views.Base"
mc:Ignorable="d"
xmlns:calVm="clr-namespace:MRWTINT.HGC.Win.ViewModels.Calendario"
x:Class="MRWTINT.HGC.Win.Views.Calendario.CalendarioView"
xmlns:draganddrop="clr-namespace:MRWTINT.HGC.Win.ViewModels.DragDropLib"
xmlns:Calendario="clr-namespace:MRWTINT.HGC.Win.Themes.Calendario"
Margin="0"
d:DesignWidth="730" Height="Auto"
Unloaded="BaseUcViewUnloaded">
<Border x:Name="border" Margin="0,0,30,0" BorderBrush="#FF8A8A8A" BorderThickness="1" CornerRadius="3" RenderTransformOrigin="0.5,0.5">
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Border.RenderTransform>
<Grid >
<Grid Background="White" Grid.IsSharedSizeScope="True">
<Grid.Resources>
<DataTemplate x:Key="DayWeekSlotTemplate">
<Border Background="Black" Opacity="0.1" MinHeight="20" MinWidth="800" />
</DataTemplate>
<DataTemplate x:Key="AllDaySlotTemplate">
<Border Background="Black" Opacity="0.1" MinHeight="44" MinWidth="800" />
</DataTemplate>
<DataTemplate x:Key="MonthSlotTemplate">
<Border Background="Black" Opacity="0.1" MinHeight="120" MinWidth="120" />
</DataTemplate>
<DataTemplate x:Key="TimeLineSlotTemplate">
<Border Background="Black" Opacity="0.1" MinHeight="800" MinWidth="110" />
</DataTemplate>
<Calendario:TimeSlotTemplateSelector
x:Key="TimeSlotTemplateSelector"
MonthSlotTemplate="{StaticResource MonthSlotTemplate}"
TimeLineSlotTemplate="{StaticResource TimeLineSlotTemplate}"
AllDaySlotTemplate="{StaticResource AllDaySlotTemplate}"
DayWeekSlotTemplate="{StaticResource DayWeekSlotTemplate}"
/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<telerik:RadBusyIndicator x:Name="busyIndicator"
Grid.Row="1" BusyContent="{DynamicResource LBL_DetalleCalendario}"
IsBusy="{Binding IsBusy}" Background="{x:Null}" BorderBrush="{x:Null}"
DisplayAfter="{Binding BusyIndicatorDelayedDisplay}">
<telerik:RadScheduler x:Name="scheduler"
TimeSlotTemplateSelector="{StaticResource TimeSlotTemplateSelector}"
draganddrop:DragDropHelper.IsDropTarget="true"
Margin="0"
Grid.Row="1"
FirstDayOfWeek="Monday" FontFamily="Arial" FontSize="10.667"
AppointmentsSource="{Binding ActividadesView}"
calVm:CalendarioEventBehaviours.CalendarioCreateActividadCommand="{Binding SaveCommand}"
calVm:CalendarioEventBehaviours.CalendarioAddActividadCommand="{Binding AddNewActividadCommand}"
calVm:CalendarioEventBehaviours.CalendarioDeleteActividadCommand="{Binding DeleteActividadCommand}"
calVm:CalendarioEventBehaviours.CalendarioEditingActividadCommand="{Binding EditingActividadCommand}"
calVm:CalendarioEventBehaviours.CalendarioEditedActividadCommand="{Binding EditedActividadCommand}"
telerik:StyleManager.Theme="{DynamicResource RadSchedulerTheme}"
ToolTip="{DynamicResource LBL_ToolTip_Calendario_Generico}"
VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch"
ShowsConfirmationWindowOnDelete="False"
OpenModalDialogs="True" Height="Auto"
AllDayAreaHeight="0"
ViewMode="{Binding CalendarioViewMode, Mode=OneWayToSource}">
<telerik:RadScheduler.MonthViewDefinition >
<telerik:MonthViewDefinition />
</telerik:RadScheduler.MonthViewDefinition>
<telerik:RadScheduler.DayViewDefinition >
<telerik:DayViewDefinition DayStartTime="07:00:00" />
</telerik:RadScheduler.DayViewDefinition >
<telerik:RadScheduler.TimelineViewDefinition >
<telerik:TimelineViewDefinition DayStartTime="07:00:00" />
</telerik:RadScheduler.TimelineViewDefinition>
<telerik:RadScheduler.RenderTransform >
<TransformGroup >
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</telerik:RadScheduler.RenderTransform>
<telerik:RadScheduler.WeekViewDefinition >
<telerik:WeekViewDefinition DayStartTime="07:00:00" />
</telerik:RadScheduler.WeekViewDefinition>
<VisualStateManager.CustomVisualStateManager>
<VisualStateManager />
</VisualStateManager.CustomVisualStateManager>
</telerik:RadScheduler>
</telerik:RadBusyIndicator>
<!-- BOTONES PARTE SUPERIOR CALENDARIO -->
<Grid x:Name="Botonera" Margin="10,4,0,0" RenderTransformOrigin="0.5,0.5" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- REFRESCAR CALENDARIO -->
<StackPanel Grid.Column="0" x:Name="PanelRefresh" Orientation="Horizontal" Cursor="Hand">
<Image x:Name="imgResfresh"
Width="16" Height="16" Source="..\..\Resources\Calendario\table_refresh.png" />
<Button x:Name="btnRefresh"
Content="{DynamicResource BTN_Refrescar}"
Style="{StaticResource ButtonStyle}"
Background="{x:Null}" FontFamily="Arial"
FontSize="10.667" Margin="0,0,5,0"
Command="{Binding RefreshCommand}" />
<Image x:Name="imgWeekends" Margin="10,0,0,0"
Width="16" Height="16" Source="..\..\Resources\Calendario\table_row_delete.png" />
<Button x:Name="btnWeekends"
Style="{StaticResource ButtonStyle}"
Background="{x:Null}" FontFamily="Arial"
FontSize="10.667" Margin="0,0,5,0"
Command="{Binding RefreshCommand}" />
</StackPanel>
<!-- /REFRESCAR CALENDARIO -->
</Grid>
<!-- /BOTONES PARTE SUPERIOR CALENDARIO -->
</Grid>
</Grid>
</Border>
Here the extract of AccountView where I'm using DataTemplates too
<DataTemplate x:Key="ImgContactoTemplate">
<Image RenderOptions.BitmapScalingMode="NearestNeighbor"
Width="16" Height="16" Margin="0,1,0,0" Source="pack://application:,,,/Resources/Cuentas/user.png" />
</DataTemplate>
<DataTemplate x:Key="ImgOportunidadTemplate">
<Image x:Name="imgTipoOportunidadEtapa"
Width="16" Height="16"
RenderOptions.BitmapScalingMode="NearestNeighbor"
Source="{Binding IDTipoEtapa, Converter={StaticResource valueToImageConverter}, ConverterParameter=EtapaOportunidadMini}"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</DataTemplate>
<DataTemplate x:Key="BtCellDataTemplate">
<Button x:Name="btnNewActivityFromOportunidad" Margin="0" Width="20" Height="20" Background="Transparent" Cursor="Hand"
Command="Cuentas:CuentaViewModel.NewActivityFromOportunidadCommand"
CommandParameter="{Binding IDOportunidad}" Padding="0"
VerticalAlignment="Center" HorizontalAlignment="Center"
Visibility="{Binding CanUserCreateNew}"
Style="{DynamicResource ButtonStyle}">
<Image RenderOptions.BitmapScalingMode="NearestNeighbor" Width="16" Height="16"
Margin="0" Source="pack://application:,,,/Resources/Calendario/calendar_add.png" />
</Button>
</DataTemplate>
So using different DataTemplates for every type forces the unloading, that makes sense, any idea to solve that?
EDIT - I have DataTemplates.xaml with DataTemplate for each type in a ResourceDictionary, example:
<DataTemplate DataType="{x:Type vmCal:CalendarioBusquedaViewModel}">
<viewsCalendario:CalendarioBusquedaView Width="Auto" MaxWidth="Infinity"/>
</DataTemplate>
Related posts I've already read:
In wpf, is there a way to execute code before the control is unloaded...? like maybe an unloading event?
How to preserve control state within tab items in a TabControl
If you want to keep state across itemdetails you should put the state in something else than the UserControls that are used to display itemdetails.
It is quite normal that the usercontrol (and thus its state) is unloaded when a different type and corresponding usercontrol is loaded.
So the patch you are suggesting is more or less a correct solution.

Wpf Bind View to ViewModel add to wpf window

I have a view that contains a ItemsControl with some textblocks inside to display the name and other information. in my window I am adding the view to the window as follows and in the code behind of the window i am binding the datacontext of the view to the view model in the MainWindow Loaded event as follows ViewOwnerSideBar.DataContext = viewModel The application compiles but when I run it I dont get data? I checked my viewmodel and I do have data in my collection that I am returning. Does anyone have any good examples of how to do this. I am going to have a sidebar view and a main view on the right displaying the details of the owner.
This is my View
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/ColorsAndBrushes.xaml"/>
<ResourceDictionary Source="/Resources/DefaultStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel >
<ScrollViewer VerticalScrollBarVisibility="Auto" >
<ItemsControl Width="250"
VerticalAlignment="Stretch"
BorderThickness="0"
ItemsSource="{Binding Path=AllOwners}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="2">
<Border Margin="2 2 0 0"
CornerRadius="4"
Background="Gray"
Opacity=".5" />
<Border BorderBrush="{StaticResource redBrush}"
BorderThickness="2"
CornerRadius="4"
Background="White"
Margin="0 0 2 2"
Padding="3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.ColumnSpan="2"
FontWeight="Bold"
Text="{Binding FullName}" />
<TextBlock Grid.Row="1"
Text=" FirstName: " />
<TextBlock Grid.Row="1"
Grid.Column="1"
Text="{Binding FirstName}" />
<TextBlock Grid.Row="2"
Text=" Email: " />
<TextBlock Grid.Row="2"
Grid.Column="1"
Text="{Binding Email}" />
</Grid>
</Border>
<Button Style="{StaticResource openButton}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
This is my window
<DockPanel>
<v:HeaderTopBar DockPanel.Dock="Top"></v:HeaderTopBar>
<!--<uc:SearchBar DockPanel.Dock="Top" />-->
<StatusBar DockPanel.Dock="Bottom">
<StatusBarItem DockPanel.Dock="Right">
<Slider x:Name="zoomSlider"
Width="125"
Value="1"
Minimum=".5"
Maximum="2" />
</StatusBarItem>
<StatusBarItem DockPanel.Dock="Right">
<TextBlock>Zoom:</TextBlock>
</StatusBarItem>
<StatusBarItem>
<TextBlock Text="{Binding StatusText}" />
</StatusBarItem>
</StatusBar>
<Expander DockPanel.Dock="Left"
ExpandDirection="Right"
IsExpanded="True"
BorderThickness="0 1 1 1"
BorderBrush="Gray"
Margin="0 2 0 0"
Padding="2">
<Expander.Header>
<TextBlock Text="Contacts"
FontSize="14"
FontWeight="Bold">
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Expander.Header>
<v:OwnerSideBar/>
</Expander>
<TabControl x:Name="tabs"
Grid.Column="2"
Margin="5 0">
<TabControl.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=zoomSlider,
Path=Value}"
ScaleY="{Binding ElementName=zoomSlider,
Path=Value}" />
</TabControl.LayoutTransform>
</TabControl>
</DockPanel>
Firstly, ensure that the AllOwners collection you are binding to is an ObservableCollection.
Also, check the Output window in Visual Studio when executing, look for First chance exceptions being caught. This will be a clue as to where your binding problem will be.
I like to put a textblock on the View bound to the Items.Count property on the ItemsControl so that you can see if it is binding and not rendering anything or not binding correctly.
Give the ItemsControl a name, then put a textblock in:
<TextBlock Text="{Binding ElementName=itemControl1,Path=Items.Count}/>
This might be something you already looked at, but you might have a binding typo, did you check your output window to see if you get any trace messages?
And I guess I'm blind but I don't see where your usercontrol is in the xaml of the second entry.

Resources