How to get Listview ItemClick Vallue in Relay Command - c#

Hi i'm working in windows store app with MVVM pattern and i have some problem in catch the listview itemclick value in relay command. Now i got the selected item value.But don't know how to get itemclickValue. Here i have attach my code.
XAML
<ListView x:Name="lstItem" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemList}" Padding="130,0,0,0" SelectedItem="{Binding SelectedItem,Mode=TwoWay}">
<Triggers:Interactions.Triggers>
<Triggers:EventTrigger EventName="SelectionChanged">
<Triggers:InvokeCommandAction Command="{Binding SelectedItemCommand}" CommandParameter="{Binding SelectedItem,Mode=TwoWay}"/>
</Triggers:EventTrigger>
</Triggers:Interactions.Triggers>
</ListView>
ViewModel Code
private Item _selectedItem;
public Item SelectedItem { get { return _selectedItem; } set { _selectedItem = value; NotifyPropertyChanged("SelectedTrends"); } }
private RelayCommand<Item> _selectedItemCommand;
public RelayCommand<Item> SelectedItemCommand
{
get
{
return this._selectedItemCommand
?? (this._selectedItemCommand= new RelayCommand<Item>(item=>
{
MessageDialog messagedialog = new MessageDialog(item.Name,"Test");
messagedialog.ShowAsync();
}));
}
}

There's a bit of redundancy here:
Option 1: Spare the CommandParameter:
private Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; NotifyPropertyChanged("SelectedTrends"); }
}
private RelayCommand _selectedItemCommand;
public RelayCommand SelectedItemCommand
{
get
{
return this._selectedItemCommand
?? (this._selectedItemCommand= new RelayCommand(() =>
{
MessageDialog messagedialog = new MessageDialog(selectedItem.Name,"Test");
messagedialog.ShowAsync();
}));
}
}
and the XAML:
<ListView x:Name="lstItem" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemList}" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" Padding="130,0,0,0">
<Triggers:Interactions.Triggers>
<Triggers:EventTrigger EventName="SelectionChanged">
<Triggers:InvokeCommandAction Command="{Binding SelectedItemCommand}" />
</Triggers:EventTrigger>
</Triggers:Interactions.Triggers>
</ListView>
Option 2: Spare the SelectedItem binding:
<ListView x:Name="lstItem" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemList}" Padding="130,0,0,0">
<Triggers:Interactions.Triggers>
<Triggers:EventTrigger EventName="SelectionChanged">
<Triggers:InvokeCommandAction Command="{Binding SelectedItemCommand}" CommandParameter="{Binding SelectedItem, ElementName=lstItem}"/>
</Triggers:EventTrigger>
</Triggers:Interactions.Triggers>
</ListView>
and remove the SelectedItem property from the ViewModel, unless you need it for something else.
EDIT
If you want to handle the click event on an item, you need to move the behavior to the ItemTemplate DataTemplate parent control, for example the grid in which the controls are placed. This lets you handle the click event on the item.

To resolve the problem I evaluated the setter attributed if there is Null reference. Then it worked fine and the event wasn't thrown anymore choose other elements.
<ListView Name="lstView" ItemsSource="{Binding Path=SimResults}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedItemCommand}" CommandParameter="{Binding SelectedItem, ElementName=lstView}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="FileUniqueID" Width="Auto" DisplayMemberBinding="{Binding Path=FileUniqueID}" />
<GridViewColumn Header="XML" Width="Auto" DisplayMemberBinding="{Binding Path=XML}" />
<GridViewColumn Header="Request" Width="Auto" HeaderStringFormat="" DisplayMemberBinding="{Binding Path=RequestShort}" />
<GridViewColumn Header="RequestDate" Width="Auto" DisplayMemberBinding="{Binding Path=RequestDate}" />
<GridViewColumn Header="Response" Width="Auto" DisplayMemberBinding="{Binding Path=ResponseShort}" />
<GridViewColumn Header="ResponseDate" Width="Auto" DisplayMemberBinding="{Binding Path=ResponseDate}" />
<GridViewColumn Header="ResendCounter" Width="Auto" DisplayMemberBinding="{Binding Path=ResendCounter}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>

Related

WPF ListView not caching images

I have a WPF application that uses a ListView with a grid that displays images directly from the web. When the list is populated the images load as expected, but as I scroll down (the list contains around 200 items on average) it starts reusing the items that aren't in view (as it should). However, this causes the images to be released from memory and as a result they get reloaded all over again when the user scrolls back up.
MainWindow.xaml
<ListView Grid.Row="3" ItemsSource="{Binding SearchResults}" Background="{StaticResource PrimaryBackground}" Foreground="{StaticResource PrimaryForeground}"
ui:GridViewSort.AutoSort="True" ui:GridViewSort.ShowSortGlyph="False" IsSynchronizedWithCurrentItem="True" VirtualizingStackPanel.IsVirtualizing="False">
<ListView.View>
<GridView>
<GridViewColumn Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate DataType="{x:Type Foo}">
<Image>
<Image.Source>
<BitmapImage CacheOption="OnDemand" UriSource="{Binding PreviewImageUrl}" />
</Image.Source>
</Image>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" ui:GridViewSort.PropertyName="Title" />
<GridViewColumn Header="Remix" DisplayMemberBinding="{Binding Remix}" ui:GridViewSort.PropertyName="Remix" />
<GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}" ui:GridViewSort.PropertyName="Artist" />
<GridViewColumn Header="Duration" DisplayMemberBinding="{Binding Duration}" ui:GridViewSort.PropertyName="Duration" />
<GridViewColumn Header="BPM" DisplayMemberBinding="{Binding Bpm}" ui:GridViewSort.PropertyName="Bpm" />
<GridViewColumn Header="Year" DisplayMemberBinding="{Binding Date}" ui:GridViewSort.PropertyName="Date" />
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="0,0,10,0" />
</Style>
</StackPanel.Resources>
<Button Command="{Binding ElementName=Window, Path=DataContext.Download}" CommandParameter="{Binding}">Download</Button>
<Button Command="{Binding ElementName=Window, Path=DataContext.CopyLink}" CommandParameter="{Binding}">Copy link</Button>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Setting the Image.Source property with a different CacheOption makes no difference. You can also see I disabled virtualization which is bad but it's the only way to have it keep the images in memory. Is there an easy way to stop this from happening while also enabling virtualization?
Add a readonly PreviewImage property to your search results item class that creates and holds the BitmapImage when it is first accessed:
public class SearchResult : INotifyPropertyChanged
{
private Uri previewImageUrl;
public Uri PreviewImageUrl
{
get { return previewImageUrl; }
set
{
previewImageUrl = value;
previewImage = null;
NotifyPropertyChanged(nameof(PreviewImageUrl));
NotifyPropertyChanged(nameof(PreviewImage));
}
}
private ImageSource previewImage;
public ImageSource PreviewImage
{
get
{
if (previewImage == null && previewImageUrl != null)
{
previewImage = new BitmapImage(previewImageUrl);
}
return previewImage;
}
}
...
}
and bind to it like this:
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding PreviewImage}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
Try this:
<Image
HorizontalOptions="CenterAndExpand"
VerticalOptions ="CenterAndExpand">
<Image.Source>
<UriImageSource Uri="{Binding Image}"
CacheValidity="14"
CachingEnabled="true"/>
</Image.Source>
</Image>

Edit TextView column on ListView WPF

I'm Using WPF.
I have ListView with TextBox column and two checkboxs columns.
I want to edit the TextBox text by double click or something else.
What is the simple way to do that?
...
<GridViewColumn Header="Name" DisplayMemberBinding={Binding Path=fullName}" Width=500>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Name="txtName"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
...
Here is a sample way of doing this...
public partial class MainWindow : Window
{
public List<string> Items { get; set; }
public MainWindow()
{
InitializeComponent();
Items = new List<string>();
LoadItems();
DataContext = this;
}
private void txtName_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextBox currentTextBox = (TextBox)sender;
if (currentTextBox.IsReadOnly)
currentTextBox.IsReadOnly = false;
else
currentTextBox.IsReadOnly = true;
}
private void LoadItems()
{
Items.Add("Coffee");
Items.Add("Sugar");
Items.Add("Cream");
}
}
<Grid>
<ListView ItemsSource="{Binding Items}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Name="txtName" Text="{Binding Mode=OneTime}" IsReadOnly="True" MouseDoubleClick="txtName_MouseDoubleClick" Width="100"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
Here is an example I have from an application that I wrote. The column JobName was to be user editable. This example allows the column to be editable and also gets rid of the border and lets the background blend into the row so it doesn't appear to have a text box in it.
Those can be edited out (BorderThickness="0" Background="Transparent").
My example binds to an MVVM ViewModel property called JobName and is set to be "TwoWay" so that changes to the view model will also reflect on the UI.
<ListView x:Name="lvJobs" HorizontalAlignment="Left" Height="628" Margin="30,62,0,0" ItemsSource="{Binding Jobs}"
SelectedItem="{Binding SelectedJob, Mode=TwoWay}" VerticalAlignment="Top" Width="335">
<ListView.View>
<GridView>
<GridViewColumn Header="Active" Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Job Name" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding JobName, Mode=TwoWay}" BorderThickness="0" Background="Transparent"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding User}" Header="User" Width="125"/>
</GridView>
</ListView.View>
</ListView>

Get Item selected after right click on context menu

How can I get the selected item from clicking a context menu bound to a listview control in WPF?
This is my markup:
<ListView Name="lvCustomerJobs">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove"
Click="cmCustomerRemoveJob"
Command="{Binding RemoveItem}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
Path=PlacementTarget.SelectedItem}" />
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Header="Status" Width="150" DisplayMemberBinding="{Binding Status}" />
<GridViewColumn Header="Booked in by" Width="150" DisplayMemberBinding="{Binding BookedInBy}" />
<GridViewColumn Header="Date Required" Width="150" DisplayMemberBinding="{Binding DateRequired}" />
</GridView>
</ListView.View>
</ListView>
This is my code behind:
private void cmCustomerRemoveJob(object sender, RoutedEventArgs e)
{
var item = ((FrameworkElement)e.OriginalSource).DataContext as User;
if (item != null)
{
MessageBox.Show(item.DateRequired + " Item's Double Click handled!");
}
}
But item IS null?
You should cast sender object to MenuItem and then use CommandParameter like this:
private void cmCustomerRemoveJob(object sender, RoutedEventArgs e)
{
var item = ((MenuItem)sender).CommandParameter as User;
if (item != null)
{
MessageBox.Show(item.DateRequired + " Item's Double Click handled!");
}
}
I bind my ListView to a collection in the model and bind the SelectedItem to the model as well.
<ListView ItemSource="{Binding CustomerCollection}" SelectedItem="{Binding SelectedCustomer}">
Then, my command method can reference SelectedCustomer as needed.
If this isn't ideal for some reason, I'd love to know!

How to verify a string changed from a textbox in listview is not the same as any exiting ones

I have a ListView box containing TextBoxes that allow users to add and change the content. How do I verify that the content that is changed is not the same as any exiting one in C# behind?
Xaml:
<ListView
x:Name="_regionQueryListBox"
Width="122"
HorizontalAlignment="Left"
VerticalAlignment="Stretch"
DataContext="{Binding}"
IsSynchronizedWithCurrentItem="True"
Style="{StaticResource ListViewRegionSelectorStyle}"
ItemsSource="{Binding Path=Model}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectionChanged="_regionQueryListBox_SelectionChanged">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Region" Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox
HorizontalAlignment="Left"
VerticalAlignment="Stretch"
MaxLength="16"
Width="110"
Margin="-2,0,0,0"
Padding="-2,0,0,0"
Text="{Binding Path=RegionName}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Yes, it is MVVM. I have a validation for adding same item and you can find the Model like below:
private void OnQueryCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if (Model.Count == 0)
{
CurrentRegionViewModel = null;
}
if (args.Action == NotifyCollectionChangedAction.Add)
{
RegionQuery addedRegionQuery = args.NewItems.OfType<RegionQuery>().FirstOrDefault();
if (addedRegionQuery != null)
{
string name = addedRegionQuery.RegionName;
while (Model.Any(q => q.RegionName == name && q != addedRegionQuery))
{
name += "*";
}
addedRegionQuery.RegionName = name;
}
}

Use Blend SDK Event triggers to fire a button click with relevant list view item MVVM

I'm trying to use the event trigger from Blend to fire a button click event of a listview item, it should work so that the item does not have to be selected for the relevant row to be referenced.
My code is...
Public void MyCommand(object obj)
{
// the tag of this has the search type
ListViewItem item = obj as ListViewItem;
// do my dreary domain work...
}
my xaml is...
<ListView ItemsSource="{Binding Path=SystemSetupItems}"
SelectedItem="{Binding Selected, Mode=TwoWay}"
MinHeight="120" >
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" />
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseClick">
<i:InvokeCommandAction CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem, AncestorLevel=1}}" Command="{Binding MyCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
but this doesn't work at all, alternatively I can do this in my xaml button definition
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding OpenWorkSpaceCommand}" CommandParameter="{Binding Path=Name}" Content="Edit..." DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}" >
</Button>
</DataTemplate>
</GridViewColumn.CellTemplate>
but this required the listview item to be previously selected, which is not the behaviour I want.
For my DataGrid I have a button on each item using the cell template. Each item is an object of type Meal. In my Meal.cs file I have an event definition like so:
public Meal()
{
RemoveMealCommand = new RelayCommand(() => RemoveMealCommandExecute());
}
public RelayCommand RemoveMealCommand
{
get;
set;
}
public delegate void RemoveMealEventHandler(object sender, EventArgs e);
public event RemoveMealEventHandler RemoveMealEvent;
private void RemoveMealCommandExecute()
{
RemoveMealEvent(this, null);
}
In my viewmodel for every meal in my list I can just add a handler to that event. And for my xaml button I just set the command to the Meal's RelayCommand.
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=RemoveMealCommand}">
<Image Width="13" Height="13" Source="/Images/delete-icon.png"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Now when you click the button the Meal is responsible for firing the event and the viewmodel is responsible for handling it.

Categories