选定的列表视图项目显示在标签中

时间:2015-10-06 12:32:21

标签: c# wpf listview

我想要做的是在“已选择”标签旁边显示所选列表视图项目的名称“如果选择了项目”。我不完全确定如何约束那个,希望有人可以提供帮助。 谢谢。

enter image description here

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; }
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

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

或者:

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