开发者

ComboBox SelectedItem display

The binding below gets and sets the selected item. It also displays items correctly, which in this case just means displaying a department's name.

However, instead of displaying the selected d开发者_如何学Pythonepartment name, it displays the selected department's ToString().

How can I fix this so the selected item displays only the department name?

Cheers,

Berryl

<ComboBox 
    Style="{StaticResource ComboBoxStyle}" 
    ItemContainerStyle="{StaticResource ComboBoxItemStyle}"

    ItemsSource="{Binding Path=Departments}" 
    SelectedItem="{Binding Path=Department, Mode=TwoWay}" 
    IsSynchronizedWithCurrentItem="True" 
    DisplayMemberPath="Name"
/>


This is because .Net framework calls the ToString() method on each observable collection item. To solve this problem you can override ToString() method in your Model like this:

public override string ToString()
{
    return this.Name;
}


I was able to fix the problem by changing the DisplayMemberPath to a DataTemplate as shown below.

Although I'm not sure why the DisplayMemberPath didn't work here, I have to assume there was some other bug in my code somewhere. Being an old question, the code has since changed and isn't worth recreating.

As an aside, I routinely use DataTemplates now, even for simple cases like this one.

Cheers,
Berryl

<ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
</ComboBox.ItemTemplate>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜