Question

Problem

I have a UserControl which contains a ToggleButton and a ComboBox. The control will allow the user to choose a sort type (via ComboBox) and a Direction (via ToggleButton). I want to be able to expose some properties of the ComboBox and more, so how do I bind the ItemsSource of the ComboBox to an Items Property of the UserControl, which I will implement myself, but also the built-in Content property---similar to how a ComboBox can do both.

UserControl

I have a user control which set-up is similar as the below code, or look here.

<UserControl x:Class="Example.DirComboBox">
    <Grid>
        <ComboBox x:Name="cbItems" />
        <ToggleButton x:Name="tbSortDir"/>
    </Grid>
</UserControl>

Control Usage

I would like to be able to use it in two ways:

1:

Adding Child Elements.

<local:DirComboBox>
    <ComboboxItem Content="Item 1"/>
</local:DirComboBox>

2:

Binding Items Property.

<local:DirComboBox Items="{Binding SortList}"/>

Alternatives

I would be willing to use alternatives, such as setting the root as ComboBox instead of UserControl but I need to expose the follow (but not sure how):

  1. Have a ToggleButton on the side,
  2. SortDirection property as a bool
  3. RoutedEvent for Ascending and Descending
Was it helpful?

Solution 2

Instead of basing my control on UserControl I changed to using a CustomControl as per the Tutorial on MSDN.

OTHER TIPS

Define Dependancy Properties for SortDirection, Items in your usercontrol. Once you have these properties in your control you can directly set them from outside like:

<local:DirComboBox Items="{Binding SortList}" SortDirection="{Binding Sort}"/>

then inside your control bind these properties to respective controls like:

<UserControl x:Class="Example.DirComboBox">
    <Grid>
        <ComboBox x:Name="cbItems" ItemsSource="{Binding Items, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}"}/>
        <ToggleButton x:Name="tbSortDir" IsPressed="{Binding SortDirection, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}"/>
    </Grid>
</UserControl>

keep the binding mode as twoway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top