Binding ElementName from context menu can't find target - c#

I am trying to bind to an element from a context menu inside a drop-down menu button (from http://shemesh.wordpress.com/2011/10/27/wpf-menubutton/). Even though outside the context menu the binding seems to work, the binding inside the context menu does not.
This is the XAML (very simplified):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" CanContentScroll="False">
<ListBox x:Name="lbScenarios" HorizontalContentAlignment="Stretch">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ItemsPresenter Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth}"/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<Expander>
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Margin="5,0,0,0" Grid.Column="0" VerticalAlignment="Center">Results</TextBlock>
<local:MenuButton Grid.Column="3" Content="Menu" Margin="5,0,0,0" VerticalAlignment="Center">
<local:MenuButton.Menu>
<ContextMenu>
<MenuItem Header="Save pie chart as image"
Command="{Binding SaveChartImageCommand}"
CommandParameter="{Binding ElementName=pieChart}" />
<MenuItem Header="Save bar chart as image"
Command="{Binding SaveChartImageCommand}"
CommandParameter="{Binding ElementName=barChart}" />
</ContextMenu>
</local:MenuButton.Menu>
</local:MenuButton>
</Grid>
</Expander.Header>
<Expander.Content>
<StackPanel>
<Image x:Name="pieChart" />
<Image x:Name="barChart" />
</StackPanel>
</Expander.Content>
</Expander>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</ScrollViewer>
</Grid>
</Window>
The binding that does not work is the {Binding ElementName=pieChart}, which is funny because the command is being found. I couldn't seem to get a RelativeSource to work, but can someone help me with getting the binding correct?

Since ContextMenu doesn't lie in same Visual tree as that of its placement target so ElementName binding won't work because it requires both controls to be in same Visual tree.
Try using x:Reference which doesn't have this constraint of to be in same visual tree.
CommandParameter="{Binding Source={x:Reference pieChart}}"
OR
use it like this
CommandParameter="{x:Reference pieChart}"
Note - x:Reference will be found in WPF 4.0 or later.

Related

Binding in WPF not propagating into usercontrol

I am new and learning WPF. I am making a demo project to learn the working of binding and dependency properties. To make it easy to understand I briefly explain this project. In solution, I have three projects. Two projects are user control and one is the main application.
This is user control for the child page
<UserControl x:Class="DefectTracking.DefectTrace"
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="450" d:DesignWidth="1200"
Grid.IsSharedSizeScope="True"
Loaded="ElementGeladen"
Name="Self">
<UserControl.Resources>
<ResourceDictionary Source="Resources.xaml" />
</UserControl.Resources>
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="{StaticResource Hintergrundfarbe}"/>
</Style>
</UserControl.Style>
<Grid DataContext="{Binding ElementName=Self}" Margin="4">
<FrameworkElement x:Name="ProxyElement"/>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!--#region Kopfzeile -->
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Ergebnisse"/>
<ColumnDefinition SharedSizeGroup="Name"/>
<ColumnDefinition SharedSizeGroup="Folgefehler" Width="*"/>
<ColumnDefinition SharedSizeGroup="Fehler"/>
<ColumnDefinition SharedSizeGroup="Aktiviert"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="2" Style="{StaticResource FolgefehlerStil}" Text="FF" />
<TextBox Grid.Column="3" Style="{StaticResource FehlerStil}" Text="Fehler"/>
<TextBox Grid.Column="4" Style="{StaticResource FehlerStil}" Text="Aktiviert"/>
</Grid>
<!--#endregion-->
<!--#region Prüfung -->
<ItemsControl Grid.Row="1" ItemsSource="{Binding Prüfungen}" Name="Prüfungselement">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Ergebnisse"/>
<ColumnDefinition SharedSizeGroup="Name"/>
<ColumnDefinition SharedSizeGroup="Folgefehler"/>
<ColumnDefinition SharedSizeGroup="Fehler"/>
<ColumnDefinition SharedSizeGroup="Aktiviert"/>
</Grid.ColumnDefinitions>
<!--#region Ergebnisse -->
<ItemsControl Grid.Column="0" ItemsSource="{Binding Ergebnisse}" Style="{StaticResource ErgebnisStil}" Background="Black" MouseDoubleClick="ItemsControl_MouseDoubleClick">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<!--#endregion-->
<!--#region Tabelle -->
<TextBox Grid.Column="1" Margin="10,0" MinWidth="50" Text="{Binding Path=Name}" Style="{StaticResource PrüfungsnameStil}"/>
<TextBox Grid.Column="2" MinWidth="40" Text="{Binding Path=Folgefehler}" Style="{StaticResource FolgefehlerStil}"/>
<TextBox Grid.Column="3" MinWidth="60" Text="{Binding Path=Fehler}" Style="{StaticResource FehlerStil}" IsReadOnly="True"/>
<CheckBox Grid.Column="4" MinWidth="40" IsChecked="{Binding Status, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="5,0,0,0"/>
<!--#endregion-->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!--#endregion-->
</Grid>
<!--#region Folgefehlerschieber -->
<Canvas>
<Thumb DragDelta="LinealVerschieben" Canvas.Left="450" Canvas.Top="0">
<Thumb.Template>
<ControlTemplate>
<Grid>
<Line X1="0" Y1="0" X2="0"
Y2="{Binding ActualHeight, Source={x:Reference ProxyElement}}"
Canvas.ZIndex="2"
Style="{StaticResource LinealStil}" Cursor="Hand">
</Line>
<Rectangle Width="11" Margin="0,0,20,0"
Height="{Binding ActualHeight, Source={x:Reference ProxyElement}}"
Style="{StaticResource AnfasserStil}" Cursor="Hand">
<Rectangle.RenderTransform>
<TranslateTransform X="-5" Y="0"/>
</Rectangle.RenderTransform>
</Rectangle>
<Label Style="{StaticResource LabelStil}" Content="{Binding Linealposition}"/>
</Grid>
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Canvas>
<!--#endregion-->
</Grid>
</UserControl>
I am just testing
<CheckBox Grid.Column="4" MinWidth="40" IsChecked="{Binding Status, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="5,0,0,0"/>
This is the user control for the child page
<UserControl x:Class="Demo.View.Dashboard"
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:Demo.View"
xmlns:vm="clr-namespace:Demo.ViewModel"
xmlns:dt="clr-namespace:DefectTracking;assembly=DefectTrackingControl"
mc:Ignorable="d"
d:DesignHeight="900" d:DesignWidth="1600"
>
<UserControl.DataContext>
<vm:DashboardViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<vm:BindingProxy x:Key="proxy" Data="{Binding}"/>
<dt:Prüfung x:Key="www"/>
</UserControl.Resources>
<Grid Background="White">
<dt:DefectTrace Margin="0,0,-321,-91">
<dt:DefectTrace.Prüfungen>
<dt:Prüfung
Status="{Binding Path=status}" />
<dt:Prüfung Name="Stabseite" />
<dt:Prüfung Name="Stosskappe" />
<dt:Prüfung Name="Druckbild"
/>
<dt:Prüfung Name="Oberfläche"
/>
</dt:DefectTrace.Prüfungen>
</dt:DefectTrace>
<CheckBox IsChecked="{Binding state, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="100,100,100,10">Test check box</CheckBox>
</Grid>
</UserControl>
Property definition which I want to bind with checkbox but it's not propagating into a user control. If I just set true and false then it works but if I bind then it doesn't work.
Any help would be highly appreciated
I believe the problem here is
<UserControl.DataContext>
<vm:DashboardViewModel/>
</UserControl.DataContext>
because that basically means using a new instance of DashboardViewModel for this particular view, so I would assume that in your code somewhere you are using a different instance of this view model in which changing the value of Status does not really matter.
If the reason is what I think it is and you want to enhance your user comfort while developing XAML files and using this to help the compiler to know the types you can use the d:DataContext something like:
d:DataContext={x:Type vm:DashboardViewModel}

WPF KeyDown does not fire in StackPanel

There are StackPanels in Listbox. MouseDown does work, but KeyDown - doesn't. KeyDown works in Listbox.
[EDIT: suggestion about "visible" didn't work for me. I post more code, maybe the problem is connected with other circumstances in the code]
<Window x:Class="PWSG_LAB_4.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:ABCD"
mc:Ignorable="d"
Title="Password Manager" Height="500" Width="700" Icon="abc.png"
Loaded="Window_Loaded">
<Window.Resources>
<local:NumberConverter x:Key="konwert"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="400"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Menu IsMainMenu="True" >
<MenuItem Header="Main menu">
<MenuItem Header="Save file" Click="MenuItem_Click" />
<MenuItem Header="Exit" Click="MenuItem_Click" />
</MenuItem>
</Menu>
<TreeView Name="Drzewo" Grid.Row="1" SelectedItemChanged="SelectionChanged">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TreeElement}" ItemsSource="{Binding Items}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" />
<TextBlock Text=" [" Foreground="Blue" />
<TextBlock Foreground="Blue">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource konwert}" Mode="OneWay">
<Binding ElementName="TreeElementItems.Count"/>
<Binding ElementName="hasla.Count"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
<TextBlock Text="]" Foreground="Blue" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<ListBox Grid.Row="1" Grid.Column="1" Name="listahasel" ItemsSource="{Binding}" AlternationCount="2" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="panelzhaslami" Orientation="Vertical" Height="90" Width="400" Background="Blue" Focusable="True" MouseRightButtonDown="mouseDownPanel" KeyDown="keydownonpanel">
<TextBlock FontSize="20" Text="{Binding placeofwork}" Padding="4"/>
<TextBlock FontSize="14" Text="{Binding login}" Padding="4"/>
<TextBlock FontSize="14" Text="{Binding password}" Padding="4"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ProgressBar Visibility="Hidden" Grid.Row="2" Grid.Column="1" Minimum="0" Height="20" Width="200" Maximum="10" Value="0" Name="Pasek" HorizontalAlignment="Right"/>
</Grid>
If your StackPanel needs to receive keyboard inputs, it must first receive the keyboard focus.
Then, from MSDN, in order for a StackPanel to receive keyboard focus, it must be focusable (Focusable = true) and visible (IsVisible = true). By default, panels are not focusable, so you need to manually set it to focusable.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Focusable="True"
MouseDown="mouseDownPanel" KeyDown="keydownonpanel">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Stretching a user control in a grid view

I have a usercontrol in a GridView in a uwp app.I want the usercontrol to be stretched in the Gridview's ItemsPanel. I tried to set the HorizontolAlignment of the usercontrol to Stretchbut no success.Someone knows the solution?
here's the xaml of the usercontrol
<UserControl
x:Class="LessonsBuild.Controls.TextItemControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LessonsBuild.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="614"
HorizontalAlignment="Stretch"
Margin="5"
Height="Auto">
<Grid Width="{Binding RelativeSource={RelativeSource Mode=TemplatedParent },Path=Width}"
Height="Auto" >
<Rectangle x:Name="DropShadow"
Margin="5,5,0,0"
Fill="{StaticResource DropShadowBrush }"/>
<Grid x:Name="Root"
Width ="{Binding RelativeSource={RelativeSource Mode=TemplatedParent },Path=Width}"
Height="Auto"
Margin="0,0,3,3"
Background="White" >
<Grid.RowDefinitions >
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<!--#region Header-->
<Grid Width="{Binding RelativeSource={RelativeSource Mode=TemplatedParent },Path=Width}"
HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions >
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitel"
Text="{x:Bind CurrentModel.Title}"
FontSize="30"
VerticalAlignment="Top" />
<StackPanel x:Name="controls"
Grid.Column="1"
Orientation="Horizontal" >
<AppBarButton x:Name="btnBold"
Icon="Bold"
Click="btnBold_Click" />
<AppBarButton x:Name="btnItalic"
Icon="Italic"
Click="btnItalic_Click" />
<AppBarButton x:Name="btnUnderline"
Icon="Underline"
Click="btnUnderline_Click" />
<AppBarButton x:Name="btnBullet"
Icon="Bullets"
Click="btnBullet_Click" />
</StackPanel>
<AppBarButton x:Name="btnDelete"
Grid.Column="2"
HorizontalAlignment="Right"
Icon="Delete"
Click="btnDelete_Click"
/>
</Grid>
<!--#endregion-->
<!--#region Content-->
<RichEditBox x:Name="txtBox"
Grid.Row="1" BorderThickness="0,1"
TextChanged="txtBox_TextChanged"
>
</RichEditBox>
<!--#endregion-->
</Grid>
</Grid>
Heres the GridViews xaml
<GridView Grid.Row="1"
Margin="30"
ItemsSource="{Binding TextControlList}" SelectionMode="None"
HorizontalContentAlignment="Stretch" />
To adjust it, modify the item of HorizontalContentAlignment as Stretch, within the 'ItemContainerStyle' (NOT within the gridview itself).
In list/gridview control, you can modify the way of item placement via this ItemContainerStyle.
<GridView x:Name="yourGridView" .... >
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</GridView.ItemContainerStyle>
</GridView>
Try to use a ListView instead of a GridView

How to make the scrollviewer work in this scenario?

Having some problems with my MVVM Application.
So the scenario is the following:
In my MainWindow.xaml, I have a ContentControl placed in a Grid Column, its content is bind to the CurrentViewModel which will be rendered to the appropriate View (in this case, Overview.xaml).
<ContentControl Grid.Row="1" Grid.Column="1" Content="{Binding CurrentViewModel}">
Within this particular view (Overview.xaml) there are multiple UserControls placed within a StackPanel.
<ScrollViewer CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
<StackPanel CanVerticallyScroll="True" CanHorizontallyScroll="True">
<views:DiagramView DataContext="{Binding Path=DiagramViewModel, Source={StaticResource Locator}}" />
<views:IncomeCollectionView DataContext="{Binding Path=IncomesViewModel, Source={StaticResource Locator}}" />
<views:ExpenseCollectionView DataContext="{Binding Path=ExpensesViewModel, Source={StaticResource Locator}}" />
<views:CheckCollectionView DataContext="{Binding Path=ChecksViewModel, Source={StaticResource Locator}}" />
<views:BalanceCollectionView DataContext="{Binding Path=BalancesViewModel, Source={StaticResource Locator}}" />
<views:VacationCollectionView DataContext="{Binding Path=VacationsViewModel, Source={StaticResource Locator}}" />
<views:KHCollectionView DataContext="{Binding Path=KhViewModel, Source={StaticResource Locator}}" />
<views:OctaviaCollectionView DataContext="{Binding Path=OctaviaViewModel, Source={StaticResource Locator}}" />
</StackPanel>
</ScrollViewer>
Each UserControl within this StackPanel has a very similar look (obviously there are more stuff in the XAML). There is no constant value regarding Width or Height within my application.
<ListView ItemsSource="{Binding Source={StaticResource groupedCollection}}" SelectedItem="{Binding CurrentItem}">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Items[0].CurrentCategory}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="12" Rows="1" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding GeneratedColumn}"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding EncryptedAmount}" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="Got paid on " />
<TextBlock Text="{Binding Date}" />
</StackPanel>
<Button Content="details"
Command="{Binding Path=DataContext.ShowDialogCommand,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
CommandParameter="QuickEdit"/>
<Button Content="remove" Command="{Binding RemoveCommand}" CommandParameter="Income removed." />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The problem is that I can't seem to make the vertical scrollviewer work. It is displayed because I make it visible, but it's disabled. Obviously the StackPanel is gonna grow indefintely, but isn't there a way for it to calculate how much space is needed? Because most of the content is just cut off right now.
So I tried to put scrollviewer in every possible place, but they're all disabled.
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<ScrollViewer>
<ContentPresenter Cursor="{TemplateBinding Cursor}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
So then I tried dropping the StackPanel implementation and tried it with a Grid.
Nope, it doesn't work either.
Obviously I'm missing some basis solution here, but just can't figure it out.
Any ideas would be appreciated, seems like a very common scenario to be honest.
Cheers
<ScrollViewer CanContentScroll="True"
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Visible">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<views:DiagramView DataContext="{Binding Path=DiagramViewModel, Source={StaticResource Locator}}" />
<views:IncomeCollectionView Grid.Row="1" DataContext="{Binding Path=IncomesViewModel, Source={StaticResource Locator}}" />
<views:ExpenseCollectionView Grid.Row="2" DataContext="{Binding Path=ExpensesViewModel, Source={StaticResource Locator}}" />
<views:CheckCollectionView Grid.Row="3" DataContext="{Binding Path=ChecksViewModel, Source={StaticResource Locator}}" />
...etc...
</Grid>
</ScrollViewer>
Edit: The DiagramView UserControl contains the following:
<UserControl x:Class="Expense.Manager.WPF.Views.DiagramView"
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:pie="clr-namespace:Expense.Manager.WPF.CustomPie"
xmlns:local="clr-namespace:Expense.Manager.WPF.Shared"
mc:Ignorable="d">
<UserControl.Resources>
<local:BoolToBrushConverter x:Key="BoolToBrushConverter" />
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Income this month: " />
<TextBlock>
<TextBlock.Text>
<PriorityBinding FallbackValue="Retrieving data...">
<Binding Path="EncryptedCurrentMonthIncome" Mode="TwoWay" IsAsync="True" />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
<pie:PieChart Data="{Binding PieChartIncomeData, Mode=TwoWay}" Width="250" PieWidth="130" PieHeight="130" Height="140" />
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Expenses this month: " />
<TextBlock>
<TextBlock.Text>
<PriorityBinding FallbackValue="Retrieving data...">
<Binding Path="CurrentMonthExpense" Mode="TwoWay" IsAsync="True" />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
<pie:PieChart Data="{Binding PieChartExpenseData, Mode=TwoWay}" Width="250" PieWidth="130" PieHeight="130" Height="140" />
</StackPanel>
<StackPanel Grid.Column="2">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding VacationsLeft}" />
<TextBlock Text=" days left" />
</StackPanel>
<ItemsControl ItemsSource="{Binding VacationsPerYearCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Margin="5, 0, 0, 0" Height="25" Width="4" Fill="{Binding Converter={StaticResource BoolToBrushConverter}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Bank savings:" />
<TextBlock Text="{Binding BankSavings}" />
</StackPanel>
</StackPanel>
</Grid>
IncomeCollectionView:
<UserControl x:Class="Expense.Manager.WPF.Views.IncomeCollectionView"
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:views="clr-namespace:Expense.Manager.WPF.Views"
mc:Ignorable="d">
<UserControl.Resources>
<CollectionViewSource x:Key="groupedCollection" IsLiveGroupingRequested="True" Source="{Binding Collection}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="CurrentCategory" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding DisplayName}" Foreground="White" FontWeight="SemiBold" Padding="5" Background="SteelBlue" />
<ListView Grid.Row="1" ItemsSource="{Binding Source={StaticResource groupedCollection}}" SelectedItem="{Binding CurrentItem}">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Items[0].CurrentCategory}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Columns="12" Rows="1" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding GeneratedColumn}"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding EncryptedAmount}" />
<TextBlock Grid.Row="1" Text="{Binding Date}" />
<Button Grid.Row="2" Content="details"
Command="{Binding Path=DataContext.ShowDialogCommand,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
CommandParameter="QuickEdit"/>
<Button Grid.Row="3" Content="remove" Command="{Binding RemoveCommand}" CommandParameter="Income removed." />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
and where it is used:
why is the listview not resizing itself after resizing the window itself?
<ScrollViewer CanContentScroll="True" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<views:IncomeCollectionView Grid.Row="1" DataContext="{Binding Path=IncomesViewModel, Source={StaticResource Locator}}" />
</Grid>
</ScrollViewer>
I tried dropping the StackPanel implementation and tried it with a Grid. Nope, it doesn't work either.
That's almost correct, apart from the last sentence. Using a Grid is half of the answer, because the StackPanel has no functionality to resize its items... you just need to inform the ScrollViewer when to scroll. Take this example:
<ScrollViewer>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Rectangle Fill="Cyan" />
<Rectangle Grid.Row="1" Fill="Green" />
<Rectangle Grid.Row="2" Fill="Red" />
<Rectangle Grid.Row="3" Fill="Blue" />
<Rectangle Grid.Row="4" Fill="Orange" />
<Rectangle Grid.Row="5" Fill="Purple" />
<Rectangle Grid.Row="6" Fill="Yellow" />
</Grid>
</ScrollViewer>
This XAML will make the ScrollViewer ScrollBar appear (once the Window.Height is small enough), but if you remove the RowDefinition.Height values (thereby giving each row a proportion of the whole Grid.Height), you'll see your previous situation where no ScrollBar appears.
Now, none of us want to hard code constant values into our UIs, but you can do this using the Auto setting on the RowDefinition.Height properties instead. Unlike these Rectangles, your controls will all have some Height, so your solution is to set each of your Grid.RowDefinitions like this:
<RowDefinition Height="Auto" />
This will provide your controls with as much space as they need within the Grid and therefore (hopefully) they will have more Height together than the ScrollViewer and therefore the ScrollViewer will display its vertical ScrollBar.

WPF Show buttons inside a selected ListItem

I'm working with a WPF application to manage our main software's versions. This application has a ListBox, and I set the ListBox.DataTemplate to each ListBoxItem has a Label and 2 Buttons inside it.
The following code shows my ListBox code:
<ListBox Grid.Row="0" SelectedItem="{Binding Path=SelectedVersion}" ItemsSource="{Binding Path=PatchList, Mode=TwoWay}" d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}"
SelectionMode="Single" IsSynchronizedWithCurrentItem="True" Margin="1" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Path=VersionNumber}" HorizontalAlignment="Left" Foreground="#FFFFFF" FontSize="19" />
<Button Grid.Column="1" Width="25" Height="25" Template="{StaticResource OnMouseOverListBoxitem}" ToolTip="Release" Command="{Binding Path=DataContext.ReleaseVersionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" HorizontalAlignment="Right" d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}" CommandParameter="{Binding}">
<ContentControl Template="{StaticResource Release}" />
</Button>
<Button Grid.Column="2" Width="25" Height="25" Template="{StaticResource OnMouseOverListBoxitem}" ToolTip="Trash" Command="{Binding Path=DataContext.DeleteVersionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" HorizontalAlignment="Right" d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}" CommandParameter="{Binding}">
<ContentControl Template="{StaticResource Trash}" />
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The problem is that I would like to show the label and the buttons ONLY for the Selected ListBoxItem.
By the way, I'm using bindings, and if you see some different code it's because I'm also using MahApp.Metro for Windows8-style.
Any suggestions?
Thank you.
try this one.
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter1" />
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Fnts}" Grid.Row="0" SelectedItem="{Binding Path=SelectedVersion}"
SelectionMode="Single" IsSynchronizedWithCurrentItem="True" Margin="1" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding}" />
<Button Content=" X " Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected, Converter={StaticResource BooleanToVisibilityConverter1}}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>

Categories