【问题标题】:get Values of one listbox item selected获取选定的一个列表框项的值
【发布时间】:2016-02-02 12:05:59
【问题描述】:

我正在编写 windows 10 通用应用程序。 我有一个列表框:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock FontFamily="Segoe UI Symbol" Text="&#x26FD;" FontSize="25"/>
            <StackPanel Orientation="Vertical">
                <TextBlock Name="txtDate" Text="{Binding Date}" FontSize="15" Margin="20,0,0,0"/>
                <TextBlock Name="txtDitance" Text="{Binding Distance}" FontSize="15" Margin="20,5,0,0"/>
            </StackPanel>
            <TextBlock Name="txtPrice" Text="{Binding Price}" FontSize="15" Margin="30,0,0,0"/>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

当我单击列表框的一个项目时,如何获取该项目的 txtDate 文本值? 我需要将所选项目的 txtDate 文本值作为字符串获取。

【问题讨论】:

  • 你有什么尝试吗?
  • 不,我绝对是初学者!
  • “不,我是绝对的初学者” 这不是 Stackoverflow 的工作方式。
  • @Krythic 你读了我所有的问题:D。

标签: c# listbox uwp uwp-xaml selecteditem


【解决方案1】:

您可以使用 ListBox 的 SelectionChanged 事件和 SelectedItem 属性来获取选定的项目。由于您在 XAML 中使用了绑定,因此您可以将所选项目强制转换为您的类以获取 txtDate 文本值。例如:

在你的 XAML 中

<ListBox x:Name="MyListBox" SelectionChanged="MyListBox_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock FontFamily="Segoe UI Symbol" FontSize="25" Text="&#x26FD;" />
                <StackPanel Orientation="Vertical">
                    <TextBlock Name="txtDate" Margin="20,0,0,0" FontSize="15" Text="{Binding Date}" />
                    <TextBlock Name="txtDitance" Margin="20,5,0,0" FontSize="15" Text="{Binding Distance}" />
                </StackPanel>
                <TextBlock Name="txtPrice" Margin="30,0,0,0" FontSize="15" Text="{Binding Price}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

在你的代码隐藏中

private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //suppose MyClass is the class you used in binding
    var selected = MyListBox.SelectedItem as MyClass;
    //Date is the property you bind to txtDate
    string date = selected.Date.ToString();
}

【讨论】:

    【解决方案2】:

    我假设当您单击列表框的一个项目时,您已经为此定义了处理程序。现在在处理程序中,

    private void handlr(object sender,SelectionChangedEventArgs e)
    {
       var obj = e.OriginalSource.DataContext as YourBoundObjectType;
       // now do whatever you want with your obj
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-10
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2010-09-23
      • 2018-12-03
      相关资源
      最近更新 更多