2

So I have this class

public class User
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string ID { get; set; }
}

And my window has this ListView called "lvUsers" and a label called "label"

<ListView Margin="10,10,237,10" Name="lvUsers" SelectionChanged="idk">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" Width="200" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" Width="Auto" DisplayMemberBinding="{Binding Age}" />
        </GridView>
    </ListView.View>
</ListView>

<Label x:Name="label" Content="Label" HorizontalAlignment="Left" Margin="380,130,0,0" VerticalAlignment="Top"/>

Then I assigned the items like this

public static List<User> users = new List<User>();

public MainWindow()
{
    InitializeComponent();

    users.Add(new User() { Name = "John", Age = 42, ID = "H42"});
    users.Add(new User() { Name = "Jacob", Age = 39, ID = "H39"});
    users.Add(new User() { Name = "Richard", Age = 28, ID = "H28"});

    lvUsers.ItemsSource = users;
}

And my question is: Is there a possibility that when I click an item in the ListView, the item's ID property will be displayed in a label called "label".

What I mean is that when I click on an item that says John and 42, I want label to say H42.

Is there a way to do it? Thank you very much for your time.

3 Answers 3

2

It would be much easier to use bindings, but I can see that you are using events: SelectionChanged="idk" in ListView. So in your code behind of window there must have (or compile-time error will occur) the method:

private void idk(object sender, SelectionChangedEventArgs e)

So you can add some code to that idk:

private void idk(object sender, SelectionChangedEventArgs e)
{
    // your code

    if (e.AddedItems.Count != 1) 
    {
        return; // or sth else
    }

    var selectedUser = (User)e.AddedItems[0];
    this.label.Text = selectedUser.ID;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a neat binding:

<Label Content="{Binding SelectedItem.ID, ElementName=lvUsers}" ...

You can also extend this to add a string format.

{Binding SelectedItem.ID, ElementName=lvUsers, StringFormat={}H{0}}

Comments

1

I'd just handle SelectionChanged event:

<ListView Margin="10,154,237,10" Name="lvUsers" SelectionChanged="lvUsers_SelectionChanged">

like this:

    private void lvUsers_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        User u = (User)lvUsers.SelectedItem;
        this.label.Content = u.ID;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.