Search code examples
c#wpfxamldatacontext

SelectedItem unknown DataContext although datacontext is set


I have a ListBox with a static ObservableCollection<HUDInfo> is bound. The DataTrigger shows the following error "PropertyPath | Cannot resolve property 'StatusConnection' in data context of type 'my window class'".

                    <ListBox 
                        x:Name="ListBoxAvailableHuDs" 
                        ItemsSource="{Binding AvailableHUDs, Source={x:Static Core:HudModel.Current}}"
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="ListBoxItem">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding StatusConnection}" Value="CanDisconnect">
                                        <Setter Property="FontWeight" Value="Bold"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </ListBox.ItemContainerStyle>
                    </ListBox>

On the Window I set the following DataContext:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

My TextBlock also can not resolve the DataContext

                    <TextBlock 
                        Text="{Binding SelectedItem.DeviceId, ElementName=ListBoxAvailableHuDs}"/>

"Cannot resolve property 'DeviceId' in data context of type 'object'"

How to set the DataContext of the ListBox to HudInfo or that the ListBoxItem is using the right DataContext?


Solution

  • At runtime the data context is resolved correctly for each list box item, however, the designer is not able to do this. You may be able to do the following:

    <Style TargetType="ListBoxItem" d:DataContext="{d:DesignInstance HudInfo }">
        <Style.Triggers>
        ...
        </Style.Triggers>
    </Style TargetType="ListBoxItem" d:DataContext="{d:DesignInstance HudInfo">
    

    with

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    

    I find this can cause an error to be shown in the designer - underlining the d:DataContext part, but it at least allows it to resolve the bindings.