Reputation: 2983
I have a ListBox
in which its items contain a TextBlock
, a Button
and an Image
. I have a Click
method on my Button
, but my problem is that it fires before the Item
of the ListBox
has changed. Here is the code for my ListBox
;
<ListBox x:Name="imageListBox" ItemsSource="{Binding CCTVImageCollection}" HorizontalAlignment="Center">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:CCTVImage}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding PictureName}" FontSize="20" FontWeight="Bold" HorizontalAlignment="Left" Margin="5"/>
<Button Grid.Column="1" Content="Directory" FontSize="16" HorizontalAlignment="Right" Margin="5" Click="OnDirectoryButtonClick"/>
<Button Grid.Column="2" Content="Live Feed" FontSize="16" HorizontalAlignment="Right" Margin="5" Click="OnCCTVButtonClick"/>
<Image Grid.Row="1" Grid.ColumnSpan="3" Source="{Binding PicturePath}" Height="400" Width="600" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And the method that is fired after clicking one of the Buttons
;
private void OnCCTVButtonClick(object sender, RoutedEventArgs e)
{
var selectedItem = imageListBox.SelectedItem as CCTVImage;
if (selectedItem != null)
{
Process.Start("chrome.exe", selectedItem.CCTVPath);
}
}
As you can see, the method relies on the ListBox.SelectedItem
and as this does not change when the Button
is clicked the SelectedItem
is dealt with as null and nothing happens. How can I enforce that the SelectedItem
changes on the Button
click?
Upvotes: 0
Views: 63
Reputation: 4474
Hope you did not find any solution for the issue.
Normally during such scenarios, what I do is either disable the button until selection of list item or get the list item from the container where the button was clicked. Try this. It should work.
private void OnCCTVButtonClick(object sender, RoutedEventArgs e)
{
var selectedItem = ((ListBoxItem)imageListBox.ContainerFromElement((Button)sender)).Content as CCTVImage;
if (selectedItem != null)
{
Process.Start("chrome.exe", selectedItem.CCTVPath);
}
}
You can also get the clicked list item by finding the visual ancestor from the visual tree during a button click.
Upvotes: 1