Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I have a ListBox with a ControlTemplate for the ListBoxItems. The ListBox is bound to an ObservableCollection inside a viewmodel. What i'm trying to do is access the viewmodel associated to the LisBox from inside the ListBoxItem Control Template.

EXAMPLE.

Here is my viewmodel:


C#
public class MainViewModel : INotifyPropertyChanged
{
    ...

    public string SampleText { ... }
    public ObservableCollection<string> Collection { ... }

    ...
}


And the View:

XML
<UserControl ...>
    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource MainViewModelDataSource}}">
        <ListBox Height="200" Width="600" ItemContainerStyle="{DynamicResource MyListBoxItemStyle}" ItemsSource="{Binding Collection}">
        </ListBox>
    </Grid>
</UserControl>


"MyListBoxItemStyle" Definition:

XML
<Style x:Key="MyListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid>
                    <ContentPresenter HorizontalAlignment="Left" Height="Auto" VerticalAlignment="Top" Width="Auto"/>
                    <TextBlock x:Name="sampleTextBlock" HorizontalAlignment="Right" TextWrapping="Wrap" Text="Sample" VerticalAlignment="Top"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


Well. I want to bind the "sampleTextBlock" Text Property to the MainViewModel.SampleText property. But what is bound to the ListBoxItem is a string because of the ObservableCollection<string>. I think maybe exists a way to access the ListBox DataContext (MainViewModel in this case) from within the ListBoxItem Control Template. Something like Text={Binding SampleText, Source={...}}

Thanks in advance.
Posted
Updated 2-Dec-14 20:21pm
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900