Search code examples
wpfdata-bindinguser-controlsitemscontrol

WPF databinding issue for itemsControl in usercontrol


I have two classes and a usercontrol.

class pvalue
{
    public string value;
    public bool selected;
    public pvalue(string v, bool s)
    {
        value = v;
        selected = s;
    }
}

class param
{
    public string name { get; set; }
    public string prefix { get; set; }
    public IList<pvalue> values { get; set; }   

    public param(string _name, string _prefix, IList<pvalue> _values)
    {
        name = _name;
        prefix = _prefix;
        values = _values;
    }
}


<UserControl DataContext="{Binding param}" >
 <Grid>...
    <ItemsControl x:Name="itemctl" ItemsSource="{Binding Path=values}">
    ...
       <ItemsControl.ItemTemplate>
             <DataTemplate>
                <ToggleButton IsChecked="{Binding Path=selected}">
                    <TextBlock Text="{Binding Path=value}" />
                </ToggleButton>
            </DataTemplate>               
        </ItemsControl.ItemTemplate>
    </ItemsControl>
 </Grid>
</UserControl>

My intention is to create the class in the application, and set it up as the datacontext of the usercontrol. But I'm very new to WPF, this is a bit over my head. The databinding isn't working - "BindingExpression path error: 'value' property not found on 'object' ''pvalue'".

Can I get some help sort out the databinding for the usercontrol? Thanks a lot.


Solution

  • Include your Solution Namespace in the UserControl definition and then include the class as a resource in Resources like this

    <UserControl.Resources> <param:SolutionName x:key="Param" /> </UserControl.Resources>

    Then Modify your code like following

    <UserControl DataContext="{Binding param}" > <Grid>... <ItemsControl x:Name="itemctl" ItemsSource="{Binding Source="{StaticResource Param}"> ... <ItemsControl.ItemTemplate> <DataTemplate> <ToggleButton IsChecked="{Binding Path=selected}"> <TextBlock Text="{Binding Path=value}" /> </ToggleButton> </DataTemplate>
    </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </UserControl>

    Hope it helps