Search code examples
c#xamlbindingdatatemplatelonglistselector

Binding background property inside template of LongListSelector


I have Class MyClass:

public class MyClass
{

    public string MyColor { get; set; }

    public class TeamOfCreators : ObservableCollection<Creator>
    {
        public string CategoryName { get; set; }

    }
    public ObservableCollection<TeamOfCreators> TeamsOfCreators { get; set; }

}

And Xaml:

<toolkit:LongListSelector ItemsSource="{Binding MyClass.TeamsOfCreators}" Height="530">
                    <toolkit:LongListSelector.GroupItemTemplate>
                        <DataTemplate>
                            <Border Background="{Binding MyColor, Converter={StaticResource NativeColorConverter}}" />      
                            <TextBlock Text="{Binding CategoryName}" Style="{StaticResource PhoneTextGroupHeaderStyle}"/>
                            </Border>
                        </DataTemplate>
                    </toolkit:LongListSelector.GroupItemTemplate>
</toolkit:LongListSelector>

How should I bind Background, to get there MyColor? How should look the binding in Background in xaml?


Solution

  • In the DataTemplate, the DataContext is an object, e.g. for a TeamCreator. TeamCreator does not have a property called MyColor - does each TeamCreator have it own color, or is there just one color for all objects?

    If each TeamCreator has its own color, move the MyColor property to the TeamCreator class.

    If you want to control the background property for all TeamCreator objects from MyClass, you'll have to access the DataContext outside of the DataTemplate.

    For example, if you've set your DataContext on, say, your Window,

    <Window x:Name="MyWindow">
    
    <toolkit:LongListSelector ItemsSource="{Binding TeamsOfCreators}">
        <toolkit:LongListSelector.GroupItemTemplate>
            <DataTemplate>
                <Border Background="{Binding DataContext.MyColor, 
                                             ElementName=MyWindow, 
                                             Converter={StaticResource NativeColorConverter}}"/>      
                    <!-- ... -->
                </Border>
            </DataTemplate>
        </toolkit:LongListSelector.GroupItemTemplate>
    </toolkit:LongListSelector>