Mostafa Mostafa - 27 days ago 7
C# Question

(MVVM/WPF) Manipulating View Elements in View-Model

I have a ListView with some Images on it that I want to works like this:
enter image description here

I did that using Command and CommandParameter for sending ListView to my View-Model and then manipulating width and height of each image:

<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding MVM.SelectedChangedCommand}" CommandParameter="{Binding ElementName=listView}"/>
</i:EventTrigger>
</i:Interaction.Triggers>


ViewModel:

private void SelectedChangedAction(object param)
{
ListView s = (ListView)param;

double j = 1;
for (int i = s.SelectedIndex - 1; i >= 0 && j >= 0; i--, j -= 0.15)
{
Pic t = (Pic)s.Items[i];
t.Width = 150 * j;
t.Height = 250 * j;
}


j = 1;
for (int i = s.SelectedIndex + 1; i < s.Items.Count && j >= 0; i++, j -= 0.15)
{
Pic t = (Pic)s.Items[i];
t.Width = 150 * j;
t.Height = 250 * j;
}
s.ScrollIntoView(s.Items[s.SelectedIndex]);
}


But as I said and you can see in View-Model, I used ListView in VM and I think that's a violation! So how can I do something like this in MVVM?

(Of course I think I can build a new controller based on ListView that could do that, though I need a simple solution like XAML or something)

Answer

Create a property for SelectedItem in ViewModel. Bind it in View's ListView. Set Bind Height and Width with a converter and move all your logic there.