How to add Command to ListBox.ItemTemplate - xaml

I have a WPF application using MVVM.
This code is from my ResourceDictionary.xaml
<DataTemplate x:Key="LogListTemplate">
<ListBox ItemsSource="{Binding LogList, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource HorizontalListBoxItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource ErrorBorders}">
<StackPanel ToolTip="{Binding Details}" Width="250">
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Details}" TextWrapping="Wrap" />
<Button Command="{Binding AddToTempDtdFileCommand}" CommandParameter="{Binding Details}" Content="Ignore" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
When I click on Button, the command does not execute. Testing confirms this is because my Button lives within a ListBox.
My problem is I can't move my button out of the ListBox for 2 reasons.
1. Asthetics/UI (the button has belong with the information)
2. Binding to the LogList is done from within the ListBox.ItemTemplate
Does any one have any suggestions?

If the command is defined in the ViewModel you can reach it by using RelativeSource. RelativeSource can find an ancestor (which is your View) so you can use its DataContext (your ViewModel).
<Button Command="{Binding DataContext.AddToTempDtdFileCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourViewClass}}}" CommandParameter="{Binding Details}" Content="Ignore" />

Related

Sending SelectedIndex of ListView to ViewModel through CommandParameter

after a quite bit of googling I haven't found answer on this problem.
I have this ListView
<ListView x:Name="itemListView" ItemsSource="{Binding History}" HorizontalAlignment="Stretch">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource Border}" Background="{ThemeResource GradientLinear}" HorizontalAlignment="Stretch">
<Grid>
<StackPanel Orientation="Vertical" Margin="10,10,10,10" HorizontalAlignment="Left" Grid.Row="0" Grid.Column="0">
<TextBlock Text="{Binding name}" />
<TextBlock Text="{Binding question}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding vrijeme}"/>
</StackPanel>
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
<SymbolIcon
HorizontalAlignment="Center"
Width="48"
Height="48"
Symbol="Delete" />
</Button>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Problem is probably in this part of the code
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
When I click Button, ListViewItem that contains that Button is not selected so I get -1 for SelectedIndex or just null if I target SelectedItem. It seems that clicking that button leaves containing ListViewItem unaffected. If I first click ListViewItem and than click button it works, SelectedItem is set in ListView of course, but I can't count user will understand that. My question is - is there any way to "force" Button to send me in CommandArgument SelectedItem or SelectedIndex. I know how to do that through code-behind but I am interested in solving this problem through MVVM.
Thanx in advance.

XAML parsing/layout rendering time very high

I've got the problem, that I create an App, that will run on Windows Phone 8.1 and Windows 10 Mobile. This App is a non-UWP Windows Store App.
The problem I have is, that I have a list of a custom control that one has another List, that is not expanded (=collapsed). That looks like this:
The red rectangles are the ContentPresenter items of the first ItemControl and the green rectangles are the ContentPresenter items of the ItemControl in the first lists items, that is not visible on startup. It will be visible after the click on the expand-button. Both ItemControls have a DataTemplate configured to present what you see in the screenshot. (XAML code below)
The main problem I have is, that if I change the Pivot to the Pivot you see at the screenshot above, there is a freeze of the app for several seconds. It depends on the device how long this freeze is. In the W10M-Emulator on my PC I don't recognize a freeze but on a Lumia 620 with WP8.1 I have a freeze of 8.5 seconds.
In the profiler of Visual Studio it looks like this (I selected the range that is the problem I am talking about):
What I am wondering about is the large orange line with "Layout". If I expand it to the "big players", there is 60-70ms for each not visible item in the profiler.
I am asking myself why this is the case, even if the items are not visible and are in the VirtualizingStackPanel. The Number of Items of the ItemSourcein this example is 3 for the first ItemControl (red boxes) and 17, 59 and 1 for the second ItemControls that are only visible of the first item is expanded.
What I am also wondering about is, that regarding the timeline, all of the Items are processed at the same time because their baseline is for all items the same. But if I scroll down the profiler timeline details, I see another Event called "Parsing" for each item. That one is not processed in parallel for each item but serial. And the parsing of the last item fits to the end of the layout-event. This parsing events look like this:
What is the reason why the parsing takes so long time? I don't think that the controls are very complex etc. and there are no code behind procedures except some string formattings.
Finally here is the XAML code:
My PivotItem on the "MainPage" of the App:
<PivotItem
Header="Echtzeit"
Margin="10,-20,10,0"
>
<Grid>
<ScrollViewer
VerticalScrollBarVisibility="Visible"
>
<ItemsControl
ItemsSource="{Binding RealtimeDepartures, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
HorizontalAlignment="Stretch"
Margin="0"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:RealtimeStation
StationName="{Binding StationName, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Departures="{Binding DepartureList, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
FontSize="{Binding DataContext.ClientFontSize, ElementName=MainPg, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</PivotItem>
The RealtimeStation Control XAML:
<UserControl
...
>
<UserControl.Resources>
<dec:BoolToVisibilityConverter x:Key="BoolToVisibilityConv"/>
</UserControl.Resources>
<Grid>
<AppBarButton
HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Column="0"
Name="btnExpand"
Icon="{Binding ExpandButtonIcon, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Click="btnExpand_Click"
IsEnabled="{Binding IsExpandButtonEnabled, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
IsCompact="True"
Margin="0,-8,-2,-4"
/>
<StackPanel
Orientation="Vertical"
Margin="48,12,0,0"
>
<TextBlock
Text="{Binding StationName, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
VerticalAlignment="Center"
FontSize="24"
/>
<TextBlock
Text="Derzeit stehen keine Abfahrten an"
FontStyle="Italic"
Visibility="{Binding ShowNoDepartures, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
/>
<TextBlock
Text="Zugausfälle vorhanden!"
Foreground="Red"
FontWeight="Bold"
Visibility="{Binding ShowTrainCanceled, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
/>
<ItemsControl
ItemsSource="{Binding DepartureList, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Margin="-48,0,0,0"
Visibility="{Binding IsExpanded, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, Converter={StaticResource BoolToVisibilityConv}}"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentPresenter>
<controls:RealtimeDeparture
DepartureDetails="{Binding}"
FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
/>
</ContentPresenter>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
And finally the RealtimeDeparture Control:
<UserControl
...
>
<Grid>
<control:DisruptionIcon
Height="24"
Width="50"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Icon="{Binding TrainIcon, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Margin="3"
/>
<StackPanel
Orientation="Vertical"
Margin="56,9,0,0"
>
<StackPanel
Orientation="Horizontal"
Margin="3,0"
VerticalAlignment="Center"
>
<TextBlock
Text="{Binding DelayTimeText, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Foreground="{Binding DelayColor, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
/>
<TextBlock
Text="{Binding DepartureDetailsText, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Margin="3,0"
/>
</StackPanel>
<TextBlock
Text="{Binding InformationText, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
Visibility="{Binding IsInformationVisible, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
Margin="3"
FontStyle="Italic"
TextWrapping="Wrap"
/>
<TextBlock
Text="Zug fällt aus!"
Foreground="Red"
FontWeight="Bold"
Visibility="{Binding IsCanceledVisible, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
Margin="3"
/>
</StackPanel>
</Grid>
</UserControl>
Does anybody has an idea how to speed up this parsing? What is the reason why it is so slow? Do I have a design issue that is disabling the virtualization-functionality of the VirtualizedStackPanel? I already tried a lot but didn't find the reason why it is so slow.
I don't think virtualization is turned on.
Try setting the CanContentScroll property to true on your ScrollViewer:
<ScrollViewer
CanContentScroll="true"
VerticalScrollBarVisibility="Visible"
>
The other option can be using e.g. ListBox which supports virtualization on its own (as far as I know it is enough to set the ItemsPanelTemplate to VirtualizingStackPanel)

how to make listbox is resizable inside its parent?

In a user control, I put a listbox which is bound to a dynamic datasource. This usercontrol will be in a popup window. I want to this list box can fill the rest of space of the window. Here is the Xaml I tried:
<ComboBox x:Name="cmbx1" Grid.Column="0" Grid.Row ="0" Margin="5"
Width="150" VerticalAlignment="Center" HorizontalAlignment="Left" SelectionChanged="filters_SelectionChanged">
......
</ComboBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="1" Grid.Row="0">
<Button Content="Test" Margin="5" Click="Button_Add" />
</StackPanel>
<DataGrid x:Name="ListGrid" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
......
</DataGrid>
<ComboBox x:Name="cmb2" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Margin="5">
......
</ComboBox>
<ListBox x:Name="lstSharing" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Margin="0,0,10,0"
Width="{Binding Width, ElementName=ListGrid}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<tkit:WrapPanel Orientation="Horizontal" MaxWidth="650" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="3" Width="Auto">
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" />
<TextBlock Text="{Binding ItemName}" Width="120" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
What I want it height and width of list box can be setup dynamically based on windows size, the items bound to list box. But it is not working properly. Initially, the listbox has no scrollbar, I need to resize window manually so that scrollbar on display. I can not dynamically to change with, so I put MaxWidth =600. Otherwise, it always display all item in one row.
How to resolve this problem?
This is untested, but I would try something like this:
<ListBox x:Name="lstSharing"
Grid.Row="3"
Grid.Column="0"
Grid.ColumnSpan="2"
Margin="0,0,10,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<tkit:WrapPanel Orientation="Horizontal"
MaxWidth="{Binding ElementName=lstSharing, Path=ActualWidth}" />
</ItemsPanelTemplate>
It's a little difficult to know whether this will work without seeing the parent containers, but it should point you in the right direction.

ComboBox in DataForm, SL4

I know that this question is what many of you already posted, but I'm still having a problem. The idea is very simple: I have a DataGrid and when I select the item in DataGrid, it should select item in ComboBox which is in DataForm. I have read many posts, and implemented few ideas in what I did, and now, I have this:
<StackPanel Grid.Column="1" Grid.Row="4" Name="stackPanel1" Margin="0,0,0,-257">
<sdk:DataGrid Name="PhysicalQuantitiesGrid"
MinHeight="100" IsReadOnly="True"
Margin="0,12,0,0"
ItemsSource="{Binding PhysicalQuantities}"
SelectedItem="{Binding Path=CurrentPhysicalQuantity, Mode=TwoWay}"
AutoGenerateColumns="False" VerticalGridLinesBrush="{x:Null}">
<sdk:DataGrid.RowDetailsTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="5">
<StackPanel Orientation="Horizontal" Margin="5">
<StackPanel Orientation="Vertical" Margin="5">
<TextBlock
FontSize="12"
Width="Auto"
Text="Base unit term"/>
<TextBlock
Foreground="CadetBlue"
FontSize="12"
Width="Auto"
TextWrapping="Wrap"
Text="{Binding Path=Unit.Term}"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5">
<TextBlock
FontSize="12"
Width="Auto"
Text="Short term"/>
<TextBlock
Foreground="CadetBlue"
FontSize="12"
Width="Auto"
TextWrapping="Wrap"
Text="{Binding Path=Unit.ShortTerm}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</sdk:DataGrid.RowDetailsTemplate>
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="Term"
Binding="{Binding Path=Term}"
FontSize="14"
Foreground="DarkBlue"
>
</sdk:DataGridTextColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,12,0,0">
<Button x:Name="NewPhysicalQuantity" Content="AddNew" Height="23" Click="NewPhysicalQuantity_Click"/>
</StackPanel>
<dataform:DataForm x:Name="PhysicalQuantityDetails"
Header="Fizicke velicine - detalji"
AutoGenerateFields="False"
AutoEdit="False"
CommandButtonsVisibility="Commit,Cancel,Edit"
Margin="0,12,0,0"
CurrentItem="{Binding Path=CurrentPhysicalQuantity}"
CancelButtonContent="Cancel"
CommitButtonContent="Commit"
>
<dataform:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<dataform:DataField Label="Physical Quantity term:">
<TextBox Text="{Binding Path=Term, Mode=TwoWay}" />
</dataform:DataField>
<dataform:DataField Label="Base unit">
<StackPanel>
<riaControls:DomainDataSource AutoLoad="True" Height="0" Name="baseUnitsDataSource" QueryName="GetBaseUnitsOrdered" Width="0">
<riaControls:DomainDataSource.DomainContext>
<myService:DomainDomainContext/>
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
<myControl:ComboBox
ItemsSource="{Binding ElementName=baseUnitsDataSource, Path=Data}"
SelectedValuePath="IDUnit"
DisplayMemberPath="Term"
SelectedValue="{Binding Path=IDUnit, Mode=TwoWay}"
>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</myControl:ComboBox>
</StackPanel>
</dataform:DataField>
</StackPanel>
</DataTemplate>
</dataform:DataForm.EditTemplate>
</dataform:DataForm>
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Right"
Margin="0,12,0,0">
<Button
Content="Save"
x:Name="SaveChangesButton"
Width="100"
Height="23"
Margin="4,0,4,0"
Command="{Binding SaveCommand}" />
</StackPanel>
</StackPanel>
So, I use MVVM with RIA. For data grid I use MVVM, and for ComboBox data context I use RIA. That is the only way to fill the ComboBox and to bind DataGrid value with ComboBox value, but in the wrong way! When I click Edit in data form, I always get ComboBox initialized to the first item. Of course, value in data grid get the same value (wrong!).
What I am doing wrong?
Thanks!
P.S. I forgot to mention that I have two tables, PhysicalQuantity and Unit, where PhysicalQuantity has one or zero Units (BaseUnit).
Lucky
You're using the wrong ComboBox.
Kyle McClellan has a far more capable ComboBox, which honestly should have been rolled out with the toolkit 2 times over by now, but there seems to be something going fishy with toolkit support as well. Please read more about it here:
http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx

Using different databinding sources within ListBox and ContextMenus

Here is the XAML:
<ListBox ItemsSource="{Binding Documents}" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Title}" FontSize="12" FontWeight="Bold" />
<TextBlock Text="{Binding ID}" FontSize="10" FontStyle="Italic" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu ItemsSource="{Binding CategoryList}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<MenuItem Command="{Binding AddDocumentToCategoryContextMenuCommand}" Header="{Binding Category.Name}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
Ok so the ListBox's ItemSource is bound to the Documents collection in the VM and properly renders the Titles and IDs
The Context Menu's ItemSource is bound to the CategoryList collection in the VM and properly renders the list of categories.
The problem I have is with the Command Binding:
Command="{Binding AddDocumentToCategoryContextMenuCommand}"
Since the ItemSource for the ContextMenu is already set, it tries to get the AddDocumentToCategoryContextMenuCommand from CategoryList. Obviously the command is not there, it is a member of the VM.
I do not want any references to the VMs or Models in the XAML. Everything is constructed using Unity and VM-View is associated in App.xaml:
<Application.Resources>
<DataTemplate DataType="{x:Type vms:FeedViewModel}">
<views:FeedView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:DocumentsViewModel}">
<views:DocumentsView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:ManagementViewModel}">
<views:ManagementView/>
</DataTemplate>
<DataTemplate DataType="{x:Type dev:DevelopmentViewModel}">
<dev:DevelopmentView />
</DataTemplate>
</Application.Resources>
How can I databind to a member of the VM from within the ContextItem.
Thanks.
UPDATED edit #1 starts Here
Here is the updated xaml (but still not working but some insight gained):
<ListBox ItemsSource="{Binding Documents}" x:Name="Results" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Title}" FontSize="12" FontWeight="Bold" />
<TextBlock Text="{Binding ID}" FontSize="10" FontStyle="Italic" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu ItemsSource="{Binding CategoryList}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<MenuItem Command="{Binding ElementName=Results, Path=DataContext.AddDocumentToCategoryContextMenuCommand}" Header="{Binding Category.Name}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
I have this example working for a simple example that does not use a ContextMenu. It appears that the ContextMenu (even though attached to the ListBox) is not part of the user control visual tree. The binding always comes back null / not found. I think the ContextMenu, because it is a floating "window" is constructed in its own tree and therefore cannot find the ListBox call "Results" in order to access the ListBox's DataContext.
Any thoughts on this? Any recommendations on how deal with?
Edit #2 Starts Here
In case you are are wondering, figured out the answer to the binding question:
This binding works:
Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.DataContext.AddDocumentToCategoryContextMenuCommand}
Hope this helps others with the same question.
One last update for completeness.
In order for the command to know which context menu item was clicked on, I had to change the xaml slightly (silly oversight):
<ListBox.ContextMenu>
<ContextMenu x:Name="Context" ItemsSource="{Binding CategoryList}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<MenuItem Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.DataContext.AddDocumentToCategoryContextMenuCommand}"
CommandParameter="{Binding Category.ID}"
Header="{Binding Category.Name}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</ListBox.ContextMenu>
Again, hope this helps others.
Use the ElementName property of the binding to specify that. You'd end up with something like this:
Command="{Binding ElementName=ViewModelObject
Path=AddDocumentToCategoryContextMenuCommand}"