Adding ComboBoxItem to a combobox inside a user control (XAML/WPF)

Posted by byte on Stack Overflow See other posts from Stack Overflow or by byte
Published on 2010-05-06T23:12:34Z Indexed on 2010/05/06 23:18 UTC
Read the original article Hit count: 426

Filed under:
|
|

I am currently learning to create custom controls in WPF. I successfully created a simple custom control using a Label and a Text Box. I was able to allow setting the Label text by DependencyProperty.

Now I am creating a user control that has a ComboBox. I need to allow adding items to this ComboBox from outside the control.

To achieve this, I tried exposing a DependencyProperty of type ItemsCollection and it will allows access to the ComboBox's Items property (the DP in my control sample is named 'CbItems'). But I get errors because Items property of Combobox is ReadOnly.

Control XAML

<UserControl x:Class="MyWpfApp.Controls.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions> 
        <Label Grid.Column="0" Content="{Binding FieldLabel}"></Label>       
        <ComboBox Name="cmb"  Grid.Column="1" Width="150"></ComboBox>
    </Grid>
</UserControl>

MainWindow XAML

<Window x:Class="MyWpfApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctl="clr-namespace:MyWpfApp.Controls"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <ctl:MyControl>
            <ctl:MyControl.CbItems>
                <ComboBoxItem>Hello</ComboBoxItem>
                <ComboBoxItem>World</ComboBoxItem>
                <ComboBoxItem>Hi</ComboBoxItem>
            </ctl:LobCombox.CbItems>
        </ctl:LobCombox>
    </Grid>
</Window>

I would like to know what the correct way is to achieve this functionality. I believe the answer to this might also help with other controls like GridView etc

Many Thanks

© Stack Overflow or respective owner

Related posts about wpf

Related posts about xaml