Reputation: 2977
I have class like the following:
class test
{
public string Name;
public string Location;
}
Through a result of query using entity framework I am getting back a collection of test objects which I am directly setting to my listbox. But using the DisplayMemberPath Iam just displaying Name value. So now the listbox is holding the whole collection of test objects but just displaying Name value.
When I am trying to bind to the selecteditem of the list box Iam getting the whole test object as a string but I just need Name value in the selecteditem result.
My XAML is as follows:
<ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedItem="{Binding Name, Mode=TwoWay}" />
My code to populate list is as follows:
LoadOperation<test> subLoadOp = context.Load(context.GetTestQuery());
lbSubSelector.ItemsSource = subLoadOp.Entities;
lbSubDistrictSelector.DataContext = SkillModel.Instance;
The DataContext to which the selectedItem is set to is having a value of the whole string representation of test object but I want the selecteditem to just return Name value as it is displaying (as i have set the displaymemberpath to Name) instead of returned the whole object in string format.
How can I achieve this?
Upvotes: 3
Views: 4850
Reputation: 939
Use following:
<ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedValuePath="@Name" />
Then you can use lbSubSelector.SelectedValue to get Name property of selected item.
Upvotes: 4
Reputation: 13594
Rather than Using ListBox, I would suggest you using the ListView with GridColumns. Following is the snippet, you might need to remodify it accordingly. But this surely will work the way you want it to :-
<ListView Name="ListView1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" MouseDoubleClick="transactionListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" >
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource gridViewHeaderColumnStyle}">
<GridView.Columns>
<GridViewColumn Width="70" Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Width="270" Header="Seller" DisplayMemberBinding="{Binding Path=Location}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
Upvotes: 0
Reputation: 8512
Please use the IsSynchronizedWithCurrentItem property on the Listbox and change the SelectedItem binding to /Name in xaml code as follows:
<ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedItem="{Binding /Name, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True"/>
Upvotes: 0