开发者

Getting Listbox Value WP7

how to get value from the textblock , which is present in listbox ....

here is the code xaml :

<ListBox Height="707" HorizontalAlignment="Left" Margin="12,0,0,0" Name="listBox1" VerticalAlignment="Top" Width="456" Background="White" Foreground="#FF09090C" ItemsSource="{Binding}" SelectionChanged="listBox1_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Name="textBlock3" FontSize="18" Foreground="Blue" Margin="2" Text="{Binding Title.Text}" TextWrapping="Wrap" />
                <TextBlock FontSize="16" Foreground="Gray" Margin="2" Text="{Binding Summary.Text}" TextWrapping="Wrap" />
                <TextBlock FontSize="1" Foreground="Gray" Margin="2" Text="{Binding Id}" TextWrapping="Wrap" Visibility="Collapsed" />
                <Button Name="h1" Content="Press" Height="10" Width="40"></Button>
                <TextBlock Foreground="Gray" Margin="2" Text="_________________________________________________开发者_StackOverflow社区_______________________________________" FontSize="8"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


You don't get the value directly from the TextBlock.
Instead what you do is bind the SelectedItem to a property on your viewmodel. To get the value of the TextBlock directly would violate the priciples of MVVM (if you are using that pattern). The viewmodel presents the data, it has no clue how that data is being rendered to the UI. IOW it has no idea there are three TextBlocks.

<ListBox Height="707" SelectedItem={Binding MyViewModelProperty} >
    ... etc ...

This means that every time the selected item is changed, the new value will be populated into the bound property on the viewmodel. All you have to do then is access that object - it's as easy as that. This means you may also possibly be able to get rid of your SelectionChanged event hookup, depending on what it is doing.

However if you insist on getting the instance of the template used to present any particular data item in a list control, then this is the way to do it programmatically:

myListBox.ItemContainerGenerator.ContainerFromItem(myDataItem);

This will return you the StackPanel and its contents, you can then either use FindName() or just enumerate the child controls to find the one you are interested in.

FrameworkElement element = myListBox.ItemContainerGenerator.ContainerFromItem(myDataItem) as FrameworkElement;
if (element != null)
    FrameworkElement child = element.FindName("myChildName");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜