WPF - Usercontrol as ListItemTemplate not filling listbox width - wpf

Just trying to get my head round WPF. I have a usercontrol which I'm using as the template for items in a listbox, however no matter what I try the usercontrol's width is always shrinking to the minimum size but I want it to fill the available width. I've found a similar query on here but it was relating just to a usercontrol not within a listbox and the solution proposed doesn't apply here.
My UserControl is defined as :
<UserControl x:Class="uReportItem"
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"
mc:Ignorable="d"
d:DesignHeight="60" d:DesignWidth="300">
<Grid >
<Border CornerRadius="3,3,3,3" BorderBrush="#0074BA" BorderThickness="1" Background="#00D6F9" Margin="0">
<DockPanel Margin="3,3,3,3">
<Grid Height="Auto">
<!-- Grid Definition-->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!-- Content -->
<!-- Top Row-->
<Button Grid.RowSpan="2">Delete</Button>
<StackPanel Orientation="Horizontal" Grid.Column="1">
<Label x:Name="Heading" Content="{Binding Heading}" FontSize="14" FontWeight="bold"></Label>
<Label x:Name="Subheading" Content="{Binding SubHeading}" FontSize="14"></Label>
</StackPanel>
<Button Grid.Column="2">Blah</Button>
<!-- Second Row-->
<Label Grid.Row="1" Grid.Column="1" x:Name="Comments">Comments</Label>
<Button Grid.Column="2">Blah</Button>
</Grid>
</DockPanel>
</Border>
</Grid>
And the implementation on the window is :
<Window x:Class="vReport"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RecorderUI"
Title="vReport" Height="300" Width="300" Background="#00BCF0">
<Window.Resources>
<DataTemplate x:Key="Record" DataType="ListItem">
<Grid>
<local:uReportItem></local:uReportItem>
</Grid>
</DataTemplate>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<local:uReport Margin="5" Grid.Row="0"></local:uReport>
<Border Grid.Row="1" BorderBrush="#0074BA" CornerRadius="3">
<ListBox Margin="5" Background="#00D6F9" BorderBrush="#0074BA" x:Name="ListRecords" ItemsSource="{Binding Items}" ItemTemplate ="{StaticResource Record}"></ListBox>
</Border>
<TextBlock Grid.Row="2" x:Name="SelectedItem" Text="{Binding Path=SelectedItem.Heading, Mode=TwoWay}"></TextBlock>
</Grid>
Any ideas?

Try setting HorizontalContentAlignment to Stretch on the ListBox:
<ListBox Margin="5" Background="#00D6F9" BorderBrush="#0074BA" x:Name="ListRecords" ItemsSource="{Binding Items}" ItemTemplate ="{StaticResource Record}" HorizontalContentAlignment="Stretch"></ListBox>

Related

WPF - ContentPresenter won't display Content

I am trying to create a container-like component. It uses the MaterialDesign Card as a container, places a title in it and allows space for Content.
<ContentControl
x:Class="Client.Components.AisCard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="450"
d:DesignWidth="800">
<materialDesign:Card
Margin="0,0,20,0"
Padding="20,20,20,30">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Text="Opmerkingen"
Style="{StaticResource MaterialDesignHeadline5TextBlock}"
FontWeight="Medium"
Margin="0,0,0,10" />
<ContentPresenter Grid.Row="1" />
</Grid>
</materialDesign:Card>
</ContentControl>
Then, I call the Component in a view and attempt to fill its Content:
<Components:AisCard
Grid.Column="0"
Grid.Row="0">
<TextBlock Text="Hello World" />
</Components:AisCard>
The result looks like this:
I expected it to look like this:
Maybe I have misunderstood the way that a ContentPresenter works. Maybe using a Component inside of a Component is not the way to go. Could anyone offer some form of assistance in the matter?
The TextBlock replaces the Card, because both just set the Content property. You would have to declare the Card as part of a ControlTemplate:
<ContentControl
x:Class="Client.Components.AisCard"
...>
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<materialDesign:Card
Margin="0,0,20,0"
Padding="20,20,20,30">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock
Grid.Row="0"
Text="Opmerkingen"
Style="{StaticResource MaterialDesignHeadline5TextBlock}"
FontWeight="Medium"
Margin="0,0,0,10" />
<ContentPresenter Grid.Row="1" />
</Grid>
</materialDesign:Card>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>

WPF ViewBox inside of a StackPanel

I am trying to display something like a score board, with team name in top 25% of a square and score taking up lower 75% (with font ratios as appropriate). I also want these controls to grow/shrink as the window gets resized.
To do this I have created a grid and split it into * and 3* rows. I have added one TextBlock to the top row and another TextBlock spanning bottom 4 rows. Then I have wrapped each TextBox in a ViewBox
This causes an application to go into a "break mode".
This shows the issue:
<Window x:Class="WpfRandoms.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:WpfRandoms"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding Teams}" HorizontalAlignment="Center" Grid.Row="0" BorderBrush="{x:Null}" Background="{x:Null}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Margin="10" Padding="10" CornerRadius="5" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="{Binding Name}" TextAlignment="Center" />
</Viewbox>
<Viewbox Grid.Row="1">
<TextBlock Text="{Binding Score}" FontSize="40" TextAlignment="Center" />
</Viewbox>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
With code-behind:
using System.Collections.Generic;
using System.Windows;
namespace WpfRandoms
{
public partial class MainWindow : Window
{
public class Team
{
public string Name { get; set; }
public int Score { get; set; }
}
public IList<Team> Teams { get; private set; }
public MainWindow()
{
InitializeComponent();
Teams = new List<Team>();
Teams.Add(new Team() { Name = "Team A", Score = 78 });
Teams.Add(new Team() { Name = "Team B", Score = 1 });
Teams.Add(new Team() { Name = "Team C", Score = 101 });
DataContext = this;
}
}
}
This seems to be caused by the StackPanel used as ItemsPanelTemplate of a ListView (without this StackPanel everything works fine but the layout is not as desired). However, I am not aware of another way of making ListView horizontal, so I am stuck with the StackPanel.
After some experimenting and reading about how ViewBox works, and how StackPanels behave I arrived at some solution (possibly not the best one).
I am wrapping my ListView in a Border, and then binding the height of a Border within the ListView's DataTemplate to the height of that outside Border.
Because of that there is a small limitation - mainly top/bottom margins cause the elements of the ListView to be trimmed. To avoid this trimming I have added padding to the Border within the DataTemplate, and then added a smaller Border within that has a background etc.
I had to also hide the vertical scrollbar of the ListView.
Here is what I have:
<Window x:Class="WpfRandoms.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"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<Border x:Name="MyBorder" Margin="10" Grid.Row="0">
<ListView ItemsSource="{Binding Teams}" HorizontalAlignment="Center" VerticalAlignment="Stretch" BorderBrush="{x:Null}" Background="{x:Null}" ScrollViewer.VerticalScrollBarVisibility="Hidden">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Margin="10, 0" Padding="10" Height="{Binding ActualHeight, ElementName=MyBorder}" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Border Background="AliceBlue" CornerRadius="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="{Binding Name}" TextAlignment="Center"/>
</Viewbox>
<Viewbox Grid.Row="1">
<TextBlock Text="{Binding Score}" FontSize="40" TextAlignment="Center"/>
</Viewbox>
</Grid>
</Border>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Border>
</Grid>
</Window>
If there is a better solution, I would greatly appreciate it :)
I'm not sure if I understand your problem exactly. If you are looking to keep the ratios between the name and score the same, you can use the "*" for the name (25%) and "3*" for the score (75%). You can also put each TextBlock in a Viewbox rather than the entire thing. To keep it simple, I replaced the converter and bindings with hard coded strings.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Border Margin="10" Padding="10" CornerRadius="5" Background="Coral">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="Home" TextAlignment="Center" />
</Viewbox>
<Viewbox Grid.Row="1" >
<TextBlock Grid.Row="1" Text="25" TextAlignment="Center" />
</Viewbox>
</Grid>
</Border>
</Grid>
I think you may have a problem with the converter you are referencing on the boarder control.
I tested your XAML without the bindings and the view box works as expected.
<Border Margin="10" Padding="10" CornerRadius="5" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Viewbox>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Team Name" TextAlignment="Center" Grid.Row="0" />
<TextBlock Text="100" FontSize="100" TextAlignment="Center" Grid.Row="1" Grid.RowSpan="3"/>
</Grid>
</Viewbox>
</Border>
Hopefully this helps!

WPF: While moving user control with images data context is lost

1) Don't move anything - everything works fine:
2) Move user control with images - the images disappeared:
3) When I move user control with images back to original place - the images are there that is everything works fine again.
The user control with images that I moved was placed inside another user control. The code looks as following:
1) The user control with images:
<UserControl x:Class="GCE.Eam.Modules.VisualCheckAnalysis.SelectedEventImageList"
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:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
xmlns:local="clr-namespace:GCE.Eam.Modules.VisualCheckAnalysis"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch">
<UserControl.Resources>
<local:PathToFileConverter x:Key="PathToFileConverter"/>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid>
<ListView Grid.Row="0"
ItemsSource="{Binding SelectedEventPhotoList}"
SelectedItem="{Binding SelectedEventPhoto}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" Name="SelectedListView">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#00000000"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#00000000"/>
</Style.Resources>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Columns="3"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<dxe:ImageEdit Source="{Binding Converter={StaticResource PathToFileConverter}}" IsReadOnly="True"
ShowBorder="False">
<dxe:ImageEdit.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.MouseDoubleClickUpperRowCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</dxe:ImageEdit.InputBindings>
</dxe:ImageEdit>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0" Stroke="Gray" StrokeThickness="0.5"/>
<Rectangle Grid.Column="1" Stroke="Gray" StrokeThickness="0.5"/>
<Rectangle Grid.Column="2" Stroke="Gray" StrokeThickness="0.5"/>
</Grid>
</Grid>
<GridSplitter Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="2"
Background="Gainsboro" ResizeDirection="Auto"/>
<Grid Grid.Row="1">
<ListView
ItemsSource="{Binding MatchingEventPhotoList}"
SelectedItem="{Binding SelectedMatchingEventPhoto}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" Name="MatchingListView">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#00000000"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#00000000"/>
</Style.Resources>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Columns="3"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<dxe:ImageEdit Source="{Binding Converter={StaticResource PathToFileConverter}}" IsReadOnly="True"
ShowBorder="False">
<dxe:ImageEdit.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.MouseDoubleClickLowerRowCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</dxe:ImageEdit.InputBindings>
</dxe:ImageEdit>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0" Stroke="Gray" StrokeThickness="0.5"/>
<Rectangle Grid.Column="1" Stroke="Gray" StrokeThickness="0.5"/>
<Rectangle Grid.Column="2" Stroke="Gray" StrokeThickness="0.5"/>
</Grid>
</Grid>
</Grid>
</UserControl>
2) The user control that contains user control with images:
<UserControl x:Class="GCE.Eam.Modules.VisualCheckAnalysis.VisualCheckAnalyzerView"
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:visualCheckAnalysis="clr-namespace:GCE.Eam.Modules.VisualCheckAnalysis"
xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol"
xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars"
xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
xmlns:dxr="http://schemas.devexpress.com/winfx/2008/xaml/ribbon"
xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
xmlns:behaviors="clr-namespace:GCE.AppFramework.Behaviors;assembly=GCE.AppFramework"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance visualCheckAnalysis:VisualCheckAnalyzerViewModel}"
d:DesignHeight="300" d:DesignWidth="300">
<dxb:BarManager>
<dxb:BarManager.Items>
<dxb:BarButtonItem x:Name="Refresh" Content="Пересчитать"
Hint="Обновить окно режима анализа ВИК"
ShowKeyGesture="False"
Glyph="Images/Recalculate_16.png"
LargeGlyph="Images/Recalculate_32.png"
Command="{Binding RecalculateCommand}"
KeyGesture="F5"
/>
<dxb:BarEditItem x:Name="MatchRadiusEdit"
EditWidth="60" ToolTip="{Binding DefaultMatchRadiusTooltip}"
Content="Rср" EditValue="{Binding MatchRadius}" >
<dxb:BarEditItem.EditSettings>
<dxe:SpinEditSettings MaskType="Numeric" IsFloatValue="True"
HorizontalContentAlignment="Right"
MinValue="{Binding MinRadius, Mode=OneWay}"
MaxValue="{Binding MaxRadius, Mode=OneWay}"
Increment="{Binding Increment, Mode=OneWay}"/>
</dxb:BarEditItem.EditSettings>
</dxb:BarEditItem>
<dxb:BarButtonItem x:Name="AddBaseTab" Content="В закладку"
Hint="Открыть закладку для выделенного объекта"
Glyph="Images/ToTab_16.png" LargeGlyph="Images/ToTab_32.png"
Command="{Binding ActivateBaseEvent}" />
<dxb:BarButtonItem x:Name="AddMatchingTab" Content="В закладку"
Hint="Открыть закладку для выделенного объекта"
Glyph="Images/ToTab_16.png" LargeGlyph="Images/ToTab_32.png"
Command="{Binding ActivateMatchingEvent}" />
</dxb:BarManager.Items>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<dxr:RibbonControl x:Name="RibbonControl" Grid.Row="0" RibbonStyle="Office2010"
PageCategoryAlignment="Left" ToolbarShowCustomizationButton="False"
ShowApplicationButton="False" ToolbarShowMode="Hide">
<dxmvvm:Interaction.Behaviors>
<behaviors:NoContextMenuDxRibbonBehavior/>
</dxmvvm:Interaction.Behaviors>
<dxr:RibbonDefaultPageCategory>
<dxr:RibbonPage x:Name="MainPage" Caption="Главная">
<dxr:RibbonPageGroup Caption="Операции" MergeOrder="{x:Static visualCheckAnalysis:VisualCheckAnalysisModule.ModuleSortHint}">
<dxb:BarEditItemLink BarItemName="MatchRadiusEdit"/>
<dxb:BarButtonItemLink BarItemName="Refresh" />
</dxr:RibbonPageGroup>
</dxr:RibbonPage>
</dxr:RibbonDefaultPageCategory>
</dxr:RibbonControl>
<Border Grid.Row="1">
<dxlc:LayoutControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Orientation="Vertical">
<dxlc:LayoutGroup VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Orientation="Vertical"
dxlc:LayoutControl.AllowVerticalSizing="True"
Width="Auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock>
<Run FontWeight="Bold" Text="Обслед. для сопоставления: "/>
<Run Text="{Binding BaseInspectionName, Mode=OneWay}"/>
</TextBlock>
<Border Grid.Row="1">
<visualCheckAnalysis:SelectedEventsList/>
<dxb:BarManager.DXContextMenu>
<dxb:PopupMenu x:Name="PopupMenu">
<dxb:PopupMenu.ItemLinks>
<dxb:BarButtonItemLink BarItemName="AddBaseTab" UserGlyphSize="Small"/>
</dxb:PopupMenu.ItemLinks>
</dxb:PopupMenu>
</dxb:BarManager.DXContextMenu>
</Border>
</Grid>
</dxlc:LayoutGroup>
<dxlc:LayoutGroup VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Orientation="Vertical"
dxlc:LayoutControl.AllowVerticalSizing="True"
Width="Auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<visualCheckAnalysis:InspectionList Grid.Row="0"/>
<Border Grid.Row="1">
<visualCheckAnalysis:MatchingEventList/>
<dxb:BarManager.DXContextMenu>
<dxb:PopupMenu x:Name="MatchedPopupMenu">
<dxb:PopupMenu.ItemLinks>
<dxb:BarButtonItemLink BarItemName="AddMatchingTab" UserGlyphSize="Small"/>
</dxb:PopupMenu.ItemLinks>
</dxb:PopupMenu>
</dxb:BarManager.DXContextMenu>
</Border>
</Grid>
</dxlc:LayoutGroup>
<dxlc:LayoutGroup>
<dxdo:DocumentGroup AllowDrag="True" AllowFloat="True" AllowMove="True"
ShowTabForSinglePage="True" ClosePageButtonShowMode="InAllTabPageHeaders">
<dxdo:DocumentPanel ShowCaption="True" Caption="Картинки для сопоставления" ShowCaptionImage="True"
CaptionImage="pack://application:,,,/GCE.Eam.OilAndGasIndustry;component/Images/Photo_16.png"
ToolTip="Картинки для сопоставления">
<visualCheckAnalysis:SelectedEventImageList/>
</dxdo:DocumentPanel>
</dxdo:DocumentGroup>
</dxlc:LayoutGroup>
</dxlc:LayoutControl>
</Border>
<dxr:RibbonStatusBarControl Grid.Row="2">
</dxr:RibbonStatusBarControl>
</Grid>
</dxb:BarManager>
</UserControl>
Where visualCheckAnalysis:SelectedEventImageList is user control with images.
As you can see I use DevExpress docking controls.
It seems to me that I loose data context when move user control with images, but I'm not sure how to make it work.
UPDATE:
<ListView Grid.Row="0"
ItemsSource="{Binding DataContext.SelectedEventPhotoList}"
SelectedItem="{Binding DataContext.SelectedEventPhoto}"
...
Try to handle the Loaded event for the SelectedEventImageList control and explicitly set its DataContext.
Something like this:
<visualCheckAnalysis:SelectedEventImageList Loaded="Control_Loaded" />
private bool _isLoaded;
private void Control_Loaded(object sender, RoutedEventArgs e)
{
if (!_isLoaded)
{
SelectedEventImageList ctrl = sender as SelectedEventImageList;
ctrl.DataContext = this.DataContext;
_isLoaded = true;
}
}

How to call a Usercontrol from another in same window in WPF ?

I have two UserControls in my project's MainWindow. In MainWindow I call the first UserControl whose content is a Button and put this FirstControl in a Grid. How can I call the second UserControl when I click on the button in FirstUserControl in MainWindow?
First UserControl :
<UserControl x:Class="BenashManage.UserControl.ButtonUserControl"
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"
Height="auto" Width="auto" RenderTransformOrigin="0,0">
<Grid>
<Border x:Name="BorderAddEdit" BorderBrush="{DynamicResource BorderBrush}" BorderThickness="5,5,5,5" CornerRadius="9,9,9,9" Background="{x:Null}">
<Grid Margin="0.2,0.2,5.4,4.2">
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<Button Content="one" TextBlock.Foreground="White" Grid.Row="1" Margin="9,9,9,9" Height="28" TextBlock.FontSize="15" Name="btn_MartyMang" Click="click_Marty"/>
</Grid>
</Border>
</Grid>
</UserControl>
Second UserControl:
<UserControl x:Class="BenashManage.UserControl.InjuredUserControl"
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"
Height="auto" Width="auto"
mc:Ignorable="d" RenderTransformOrigin="0,0" FontFamily="Arial" FontSize="14" TextBlock.Foreground="White">
<Grid VerticalAlignment="Top" Height="auto" Width="360" HorizontalAlignment="Right">
<Border x:Name="BorderAddEdit" Margin="6,2,6,6" BorderThickness="5,5,5,5" CornerRadius="9,9,9,9" Background="{x:Null}">
<Grid VerticalAlignment="Center" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="20.8"/>
</Grid.ColumnDefinitions>
<TextBlock TextWrapping="Wrap" Text=":jjj" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,4,-0.4,3"/>
<TextBox Grid.Row="6" TextAlignment="Right" VerticalAlignment="Center" Margin="3,2.8,2.2,2.2" />
</Grid>
</Border>
</Grid>
</UserControl>
MainWindow:
<Window x:Class="BenashManage.MartyrManage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:BenashManage.UserControl"
Title="MartyrManage" Height="550" Width="550" Style="{DynamicResource ModalWindowStyle}" Loaded="Window_Loaded_1">
<Window.CommandBindings>
<CommandBinding Command="Close"
Executed="CloseCommand_Executed"/>
</Window.CommandBindings>
<Grid >
<Grid Margin="179,10,10.4,10" HorizontalAlignment="Center" VerticalAlignment="Center"
*******
Height="456" Width="357" Name="MoveToUserControl" ></Grid>
<Grid Margin="10,71,372.4,67" HorizontalAlignment="Center" VerticalAlignment="Center" Height="338" Width="auto" Name="ButtonManage" >
<controls:FirstUserControl Margin="0,0,0,92">
</controls:FirstUserControl>
</Grid>
</Grid>
</Window>
There are a couple of ways you can do this:
1) Get the parent of the UserControl and then get its children.
(((control1).Parent as Panel).Children[1] as UserControl)
2) Raise an event in the one UserControl which is handled by MainWindow to call the function in the other UserControl.

MVVM + UserControl + UserControl + DependencyProperty

I have a user control which displays addresses housed inside of another page that is bound to a viewmodel. The viewmodel has a primitive User which has a collection of Address objects. The User control will reside on several pages so I would like to be able to bind it to the address list via a dependency property. While my current solution is working, something about it just doesn't feel right and I thought I'd ask for a second opinion. I have chopped out a lot of code for brevity's sake.
Basically the page binds to the dependency property in the usercontrols code behind which then updates the usercontrol's datagrid by setting it's itemsource. This seems to me to break the basic tenants of MVVM.
AddressListView control:
<UserControl x:Class="Insight.Controls.AddressListView"
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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:tk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
xmlns:command="clr-namespace:PrismFramework.Implementors.Commanding;assembly=PrismFramework"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="840">
<UserControl.Resources>
<command:ObservableCommand x:Name="EditAddressCommand" Value="{Binding EditAddressCmd}"/>
<command:ObservableCommand x:Name="DeleteAddressCommand" Value="{Binding DeleteAddressCmd}"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid Name="dgAddresses"
Height="Auto"
Width="Auto"
AutoGenerateColumns="False"
HeadersVisibility="None" >
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn x:Name="dgcAddresses"
Width="*" >
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border x:Name="bdrAddress"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="Auto"
BorderBrush="Silver"
BorderThickness="1"
Padding="0"
Margin="1,1,1,1">
<Grid x:Name="grdAddressItem"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="Auto">
<Grid.RowDefinitions>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
<RowDefinition Height="17" MinHeight="17"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="55" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Padding="0,0,5,0" Text="Type:" TextAlignment="Right" />
<TextBlock Grid.Column="1" Padding="0" Text="{Binding Path=AType}" Grid.ColumnSpan="2" />
<TextBlock Grid.Row ="1" Grid.Column="0" Padding="0,0,5,0" Text="Address 1:" TextAlignment="Right" />
<!-- List Of Similar Fields ->
<Grid x:Name="grdAddressEditOptions"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="Auto"
Grid.Column="3"
Grid.RowSpan="7" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="btnEdit"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="Auto"
Grid.Row="0"
Padding="4,5,4,8"
Margin="0,8,10,0"
Command="{Binding Value, Source={StaticResource EditAddressCommand}}"
CommandParameter="{Binding}" >
<Button.Content>
<Image x:Name="btnEditIcon"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Height="Auto"
Width="Auto"
Source="/Insight.ModuleUser;component/Images/edit.png"
Visibility="Visible" />
</Button.Content>
</Button>
<Button x:Name="btnDelete"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Width="Auto"
Grid.Row="2"
Padding="4,5,4,8"
Margin="0,0,10,5"
Command="{Binding Value, Source={StaticResource DeleteAddressCommand}}"
CommandParameter="{Binding}" >
<Button.Content>
<Image x:Name="btnDeleteIcon"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Height="Auto"
Width="Auto"
Source="/Insight.ModuleUser;component/Images/delete.png"
Visibility="Visible" />
</Button.Content>
</Button>
</Grid>
</Grid>
</Border>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
AddressListView code behind:
Imports System.Collections.ObjectModel
Imports Insight.DataServices.Primitives
Partial Public Class AddressListView
Inherits UserControl
Public ReadOnly AddressesProperty As DependencyProperty = DependencyProperty.Register("Addresses", GetType(ObservableCollection(Of Address)), GetType(AddressListView), New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnAddressesChanged)))
Public Sub New()
InitializeComponent()
End Sub
Public Property Addresses As ObservableCollection(Of Address)
Get
Return DirectCast(GetValue(AddressesProperty), ObservableCollection(Of Address))
End Get
Set(value As ObservableCollection(Of Address))
SetValue(AddressesProperty, value)
End Set
End Property
Public Sub OnAddressesChanged()
Me.dgAddresses.ItemsSource = Addresses
End Sub
End Class
Base page:
<UserControl x:Class="Insight.ModuleUser.Views.EditUserView"
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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:prism="clr-namespace:Microsoft.Practices.Prism.Interactivity.InteractionRequest;assembly=Microsoft.Practices.Prism.Interactivity"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cm="clr-namespace:System.ComponentModel;assembly=System.Windows"
xmlns:data="clr-namespace:System.Windows.Data;assembly=System.Windows"
xmlns:vm="clr-namespace:Insight.ModuleUser.ViewModels"
xmlns:command="clr-namespace:PrismFramework.Implementors.Commanding;assembly=PrismFramework"
xmlns:controls="clr-namespace:Insight.Controls;assembly=Insight.Controls"
xmlns:modalDialogs="clr-namespace:Insight.Controls.ModalDialogViews;assembly=Insight.Controls"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="1144"
d:DataContext="{d:DesignData /Insight.ModuleUser;component/SampleData/EditUserViewModelSampleData.xaml}">
<UserControl.Resources>
<command:ObservableCommand x:Name="OpenProjectCommand" Value="{Binding OpenProjectCmd}"/>
<command:ObservableCommand x:Name="OpenPaymentCommand" Value="{Binding OpenPaymentCmd}"/>
<command:ObservableCommand x:Name="OpenInvoiceCommand" Value="{Binding OpenInvoiceCmd}"/>
<command:ObservableCommand x:Name="OpenPaymentItemCommand" Value="{Binding OpenPaymentItemCmd}"/>
<command:ObservableCommand x:Name="EditPhoneCommand" Value="{Binding EditPhoneNumberCmd}"/>
<command:ObservableCommand x:Name="DeletePhoneCommand" Value="{Binding DeletePhoneNumberCmd}"/>
<command:ObservableCommand x:Name="EditEmailAddressCommand" Value="{Binding EditEmailAddressCmd}"/>
<command:ObservableCommand x:Name="DeleteEmailAddressCommand" Value="{Binding DeleteEmailAddressCmd}"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" >
<controls:AddressListView x:Name="ctrlAddressListView"
Addresses="{Binding User.Addresses}" />
</Grid>
</UserControl>
This seems a perfectly reasonable approach. However, you could use binding in your user control view, rather than setting the items source in code.
To do this you need to set the DataContext of the user control to be your user control type. This could be done either in the code behind for the user control (setting this.DataContext = this), or through element binding in XAML:
<UserControl
...
x:Name="MyName"
DataContext="{Binding ElementName=MyName}"
However, my approach would be not to use a user control at all, as all you're really talking about is view composition and reusing a particular section of the view between other views.
View composition is extremely straightforward with an MVVM framework such as Caliburn.Micro. In this case you would have an AddressViewModel and AddressView, and use a ContentControl to inject the AddressView into the base view:
<ContentControl x:Name="AddressViewModel" />

Resources