Bind combobox elements to data source

亡梦爱人 提交于 2019-12-11 06:46:52

问题


I have a combobox which hosts a textblock child element. I want to bind the textblock inside the combobox to a property called ResultList. I tried the code below, but it doesn't work. What have I missed out?

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

回答1:


So, to sum all the comments up:

You need to bind the list to ItemsSource of comboBox.

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

And set TextBlock in the ItemTemplate to something like:

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



回答2:


You can't set both the DataContext and the Text property to the same value:

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

You can try this:

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

But this might be better:

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

Of course, it is hard to answer when you haven't provided all of the necessary information, such as what has been asked in the comments.



来源:https://stackoverflow.com/questions/18825100/bind-combobox-elements-to-data-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!