Reputation: 683
I have encountered a major problem for myself in the learning process of WPF bindings. I have to create an application that uses a Listview which look like this:
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="75" DisplayMemberBinding="{Binding ID}" />
<GridViewColumn Header="Name" Width="170" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Price" Width="100" DisplayMemberBinding="{Binding Price}" />
<GridViewColumn Header="Reseller" Width="Auto" DisplayMemberBinding="{Binding Reseller}" />
</GridView>
</ListView.View>
In the codebehind file I have a property:
public Product seletedRow
{
get { return m_Product; }
set { m_Product = value; PropertyChanged("Product"); }
}
The goal would be to set this property to the selected row of the listView and then show the fields of this property in 4 textboxes. If I set this property manually from code I can display the information in the textboxes but I can't figure out how to bind the object from the ListView.SelectedItem. As far as I have found I should be using OneWayToSource binding mode but I have no idea how.
I'm also opened to other solutions, as long as I can use it in MVVM pattern.
Upvotes: 0
Views: 797
Reputation: 26362
It's probably better to do something like this. That way you don't even need any code-behind.
{Binding ElementName=myListView, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}
You'll need to assign ListView a name like this.
<ListView Name="myListView">
It would look something like this.
<ListView Name="myListView">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="75" DisplayMemberBinding="{Binding ID}" />
<GridViewColumn Header="Name" Width="170" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Price" Width="100" DisplayMemberBinding="{Binding Price}" />
<GridViewColumn Header="Reseller" Width="Auto" DisplayMemberBinding="{Binding Reseller}" />
</GridView>
</ListView.View>
</ListView>
<TextBox Text="{Binding ElementName=myListView, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}"/>
Edit:
If you wan't to expand on the logic you probably want to look into using ACB
, as with ACB
you could do something like this.
acb:CommandBehavior.Event="SelectedItemChanged"
acb:CommandBehavior.Command="{Binding SelectedItemChanged}"
acb:CommandBehavior.CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=SelectedItem}"
This would essentially allow you to store the specific SelectedItem
each time you choose a new item on the list.
http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
Upvotes: 1