WPF: How to bind object to ComboBox

There are several ways to tell the framework what to display

1) Use DisplayMemberPath on the ComboBox (this will display the named property):

<ComboBox ItemsSource="{Binding Path=Clients}" 
          DisplayMemberPath="Name"
/>

2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display, rather than just a property:

<ComboBox ItemsSource="{Binding Path=Clients}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Green" BorderThickness="1" Padding="5">
                <TextBlock Text="{Binding Path=Name,StringFormat="Name: {0}"}" />
            </Border>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

3) Add a ToString() override to source class. Useful if you always want to display the same string for a given class. (Note that the default ToString() is just the class type name, which is why you see “TheProtect.UserControls.Client”.)

public class Client
{
    // ...

    public override string ToString()
    {
        return string.Format("{0} ({1})", Name, ID);
    }
}

4) Add a DataTemplate to the XAML resources. This is useful for associating a given class type with a more complex or stylized template.

<UserControl xmlns:local="clr-namespace:TheProject.UserControls">
    <UserControl.Resources>
        <DataTemplate DataType="local:Client">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </UserControl.Resources>

    // ...

</UserControl>    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)