将ListView ItemTemplate中的一些文本复制到UWP中的字符串

时间:2017-04-03 17:57:07

标签: c# listview uwp win-universal-app

我在XAML中有ListView

<ListView x:Name="listView" Margin="10,72,10,120" Background="#7F000000" BorderBrush="#FF00AEFF" BorderThickness="1">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel BorderThickness="0,0,0,1">
                        <TextBlock Text="{Binding SSID}" Foreground="#FF067EB6" Margin="0,5,0,0"></TextBlock>
                        <TextBlock Text="{Binding BSSID}" Foreground="#FF067EB6"></TextBlock>
                        <TextBlock Text="{Binding NumOfBars}" Foreground="#FF067EB6"></TextBlock>
                        <TextBlock Text="{Binding WpsPin}" Foreground="#FF067EB6" Margin="0,0,0,5"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

在背后的代码中有类似的东西:

class Networks
{
    public string SSID { get; set; }
    public string BSSID { get; set; }
    public string NumOfBars { get; set; }
    public string WpsPin { get; set; }
}

这个使用ListView

listView.ItemsSource = null;
ObservableCollection<Networks> nets = new ObservableCollection<Networks>();
nets.Add(new Networks() { SSID = "SSID: " + networkSSID, BSSID = "BSSID: " + network.Bssid, NumOfBars = "Signal: " + network.SignalBars.ToString() + "/4", WpsPin = "WPS Pin: " + wpspin });
listView.ItemsSource = nets;

现在,我想获取ItemSource中所选项目的内容并将其放在一个字符串中。例如,我想获得&#34; WpsPin&#34;所选项目的值。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以订阅ListView.SelectionChanged事件并在以下代码中实现它:

XAML:

<ListView ... SelectionChanged="SelectionChanged">

C#:

private void SelectionChanged(object sender, SelectionChangedEventArgs e) {
    Networks network = e.AddedItems.FirstOrDefault() as Networks;
    if (network == null) return;

    System.Diagnostics.Debug.WriteLine(network.WpsPin);
}