获取 combobox.itemtemplate 中文本块的内容

Get the content of a textblock in a combobox.itemtemplate

我已经设法使用带有数据绑定的 TextBlock 项目将不同的字符串日期放入 ComboBox 中,然后我想在我的 ComboBox 中获取所选项目的文本,这是我的 WPF 代码:

<ComboBox ItemsSource="{Binding ListProgram, ElementName=Window}" x:Name="date">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Name="test" Text="{Binding Date}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我试过了,但它什么也没显示:

Console.WriteLine(date.Text);

我也试过了,还是不行:

Console.WriteLine(test.Text);

非常感谢,一位法国初级程序员。

date 是一个 ComboBox,所以 date.ToString() 到 return System.Windows.Controls.ComboBox 是很自然的。

您想获取 日期 的所选项目的值,这不是控件本身。

首先,可以省略DataTemplatestrings 自动变成 TextBoxes。只需指定 DisplayMemberPathSelectedValuePath(在您的情况下为 "Date",但您当然可以选择不同的属性),WPF 将处理其余部分。

  • DisplayMemberPath 告诉 ComboBox 要使用 显示 项目的 属性 项目。
  • SelectedValuePath 告诉 ComboBox 属性 用于 SelectedValue
<ComboBox ItemsSource="{Binding ListProgram, ElementName=Window}"
    DisplayMemberPath="Date" SelectedValuePath="Date" x:Name="date">
</ComboBox>

在您的代码中,您可以通过以下方式获取所选项目(或其价值):

date.SelectedValue // will return the "Date" property of the selected Item
date.SelectedItem  // will return the item itself
date.Text          // will return the string it is displaying