Search code examples
c#xamldata-bindingdatatemplatewindows-phone-8.1

xaml windows phone 8.1 binding to page from template


I am trying to bind the visibility on a checkbox that is in a DataTemplate (used in a listbox) to a property on my ViewModel. I want to show and hide all the checkbox's with the one property.

After all my searching I can't find the solution. Here is the non-working code that I have so far.

<DataTemplate x:Key="GroupTemplate">
    <Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="40"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <CheckBox  Visibility="{Binding CheckboxVisible, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BooleanToVisibilityConverter}}"  Grid.Column="0" />
        <TextBlock  Text="{Binding GroupName}" Grid.Column="1"/>
    </Grid>
</DataTemplate>

public class GroupListViewModel : ViewModelBase
{
    private bool _checkboxVisible;
    public bool CheckboxVisible
    {
        get
        {
            return _checkboxVisible;
        }
        set
        {
            Set(() => CheckboxVisible, ref _checkboxVisible, value);
        }
    }               
    // ...
}   

Solution

  • is GroupListViewModel the DataContext of the items control that has this data template? Then you can add a name to the items control and access it by name, for example:

    <GridView x:Name="items">
    ...
    <CheckBox  Visibility="{Binding DataContext.CheckboxVisible, ElementName=items, Converter={StaticResource BooleanToVisibilityConverter}}"  Grid.Column="0" /