【问题标题】:Bind combobox elements to data source将组合框元素绑定到数据源
【发布时间】:2013-09-20 10:20:18
【问题描述】:

我有一个组合框,其中包含一个文本块子元素。我想将组合框中的文本块绑定到一个名为 ResultList 的属性。我尝试了下面的代码,但它不起作用。我错过了什么?

    <ComboBox x:Name="Test" HorizontalAlignment="Left" Margin="79,42,0,0" VerticalAlignment="Top" Width="344" 
              IsEditable="True">
        <ComboBox.Resources>
            <system:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">0</system:Double>
        </ComboBox.Resources>
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}" >
                <Setter Property="Background" Value="#FFFFFF"/>
                <Setter Property="BorderThickness" Value="0" />
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=ResultList, Mode=OneWay}" DataContext="{Binding Path=ResultList, Mode=OneWay}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

【问题讨论】:

  • 你的ItemsSource在哪里comboBox?我猜你会喜欢将ResultList 绑定到ItemsSource
  • 什么对象有ResultList属性? DataContext 和/或ItemsSource 如何在ComboBox 上设置?
  • 是的,我可以绑定到 ItemSource,这很有效,但是我该如何绑定这个我的文本块?
  • 我假设ResultList 是一个项目列表,因此将其绑定到文本块没有多大意义。如果您要做的是显示组合框中的每个项目,那么就像其他人指出的那样,您应该绑定ComboBoxItemsSource。此外,如果您只是将其显示为纯文本,comboBox 会为您完成,无需使用DataTemplate ...
  • @Prof,您的意思是当您将ItemsSource 绑定到您的comboBox 时,您不知道要绑定textblock 什么?只需使用&lt;TextBlock Text="{Binding}"/&gt;

标签: c# wpf binding combobox textblock


【解决方案1】:

所以,总结所有的cmets:

您需要将列表绑定到comboBoxItemsSource

<ComboBox x:Name="Test" ItemsSrouce="{Binding ResultList}" ....>

并将ItemTemplate 中的TextBlock 设置为:

<TextBlock Text="{Binding Path=Age}" ..../> 
<TextBlock Text="{Binding Path=Name}" ..../> 

【讨论】:

  • 是的,我实际上只是想出了如何做这些领域。你甚至不需要指定路径
  • @Prof,正确,只是个人偏好,我喜欢在 ItemTemplate 中使用Path
  • 简单易行。我印象深刻,这只花了大约 25 分钟就解决了。大家
【解决方案2】:

您不能将DataContext Text 属性设置为相同的值:

"{Binding Path=ResultList, Mode=OneWay}" 

你可以试试这个:

<TextBlock Text="{Binding, Mode=OneWay}" DataContext="{Binding Path=ResultList}" />

但这可能会更好:

<TextBlock Text="{Binding Path=ResultList, Mode=OneWay}" />

当然,如果您没有提供所有必要的信息,例如 cmets 中询问的内容,则很难回答。

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多