Search code examples
c#xamluwpuwp-xamlwindows-community-toolkit

How do you access the DataContext of a ListViewItem in the style of the ListViewItem?


I have an ObservableCollection<Foo> fooList, and the following code for a MasterDetailsView, which is just a fancier ListView:

<controls:MasterDetailsView
            Grid.Row="1"
            x:Name="MasterDetailsViewControl"
            ItemsSource="{x:Bind fooList}"
            SelectedItem="{x:Bind Selected, Mode=OneWay}"
            ItemTemplate="{StaticResource ItemTemplate}"
            DetailsTemplate="{StaticResource DetailsTemplate}"
            NoSelectionContentTemplate="{StaticResource NoSelectionContentTemplate}"
            BorderBrush="Transparent">
    <controls:MasterDetailsView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Background">
                <Setter.Value>
                    <Binding Path="PathToFooBrushGoesHere" />
                </Setter.Value>
            </Setter>
        </Style>
    </controls:MasterDetailsView.ItemContainerStyle>
</controls:MasterDetailsView>

Each foo has an individual property foo.Brush, which I want to use to paint the background of the ListViewItem. I can't work out what I need to put in PathToFooBrushGoesHere in order to get the ListViewItem to access the property of foo that has the Brush.

I had the idea that it might be doable by setting a different DataContext, but I couldn't work out how I'd be able to access the DataContext of the ItemTemplate in the ListViewItem style.

How should one go about this styling?


Solution

  • You can implement this effect by binding the Brush property to the ItemTemplate of MasterDetailsView.

    Fristly, change the MasterDetailsView.ItemContainerStyle as the following to setting the VerticalContentAlignment and HorizontalContentAlignment properties of ListViewItem to Stretch,

    <controls:MasterDetailsView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </controls:MasterDetailsView.ItemContainerStyle>
    

    Then bind the Brush property to the ItemTemplate of MasterDetailsView.

    <DataTemplate x:Key="ItemTemplate" x:DataType="local:Foo">
        <Grid Background="{x:Bind Brush}">
            <TextBlock Text="ItemTemplate"/>
        </Grid>
    </DataTemplate>