简体   繁体   中英

selected listview item displays in label

What I'm wanting to do is display the selected listview item's name 'if an item is selected' next to the 'Selected' label. I'm not entirely sure how to go about binding that, hope someone can help. Thank you.

在此处输入图片说明

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="240" Width="230">
    <Grid>
        <ListView Margin="10,10,10,43" Name="lvDataBinding">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <TextBlock Text="Name: " />
                        <TextBlock Text="{Binding Name}" FontWeight="Bold" />
                        <TextBlock Text=", " />
                        <TextBlock Text="Age: " />
                        <TextBlock Text="{Binding Age}" FontWeight="Bold" />
                        <TextBlock Text=" (" />
                        <TextBlock Text="{Binding Mail}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
                        <TextBlock Text=")" />
                    </WrapPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Label Content="Selected:" HorizontalAlignment="Left" Margin="10,172,0,0"/>
        <Label Content="" HorizontalAlignment="Left" Margin="72,172,0,0" Width="140"/>
    </Grid>
</Window>

CS

using System.Collections.Generic;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<User> items = new List<User>();
            items.Add(new User() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com" });
            items.Add(new User() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com" });
            items.Add(new User() { Name = "Sammy Doe", Age = 13, Mail = "sammy.doe@gmail.com" });
            lvDataBinding.ItemsSource = items;
        }
    }

    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Mail { get; set; }
    }
}

Try this:

<Label Content="{Binding SelectedItem.Name, ElementName=lvDataBinding}" .../>

Or:

<Label Content="{Binding ElementName=lvDataBinding, Path=SelectedItem.Name}" .../>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM