开发者

Type name showing up in WPF drop-down list

I'm binding a List<SelectItem> to a ComboBox using MVVM. The开发者_StackOverflow社区 combobox has the right value and looks fine. However, when I click on the down button to see all the options in the combobox, I get a list of 10 items that each read MyNamespace.SelectItem. If I select #2, the value in the combobox then reads 2.

Here's the code for SelectItem:

public class SelectItem
{
    public string Value { get; set; }
    public string Display { get; set; }
}

My XAML:

<ComboBox ItemsSource="{Binding Path=MyList}" DisplayMemberPath="Display" SelectedValue="{Binding Path=MyListValue, Mode=TwoWay}" />

And here's where I queue up a list of SelectItems:

        MyList= new List<SelectItem>();
        for (int i = 1; i <= 10; i++)
        {
            var page = new SelectItem()
            {
                Display = i.ToString(),
                Value = i.ToString()
            };
            MyList.Add(page);
            if (i == 1)
                MyListValue = page;
        }


Check for any typo.

With following code:

public class SelectItem
{
    public string Value { get; set; }
    public string Display { get; set; }
}

public class SelectItemViewModel
{
    public List<SelectItem> MyList { get; set; }
    public SelectItem MyListValue { get; set; }

    public SelectItemViewModel()
    {
        MyList = new List<SelectItem>();
        for (int i = 1; i <= 10; i++)
        {
            var page = new SelectItem()
            {
                Display = i.ToString(),
                Value = i.ToString()
            };
            MyList.Add(page);
            if (i == 1)
                MyListValue = page;
        }
    }
}

Initialization:

public MainWindow()
{
    DataContext = new SelectItemViewModel();
}

XAML:

<ComboBox HorizontalAlignment="Center"
            VerticalAlignment="Center"
            ItemsSource="{Binding Path=MyList}"
            DisplayMemberPath="Display"
            SelectedValue="{Binding Path=MyListValue, Mode=TwoWay}" />

I was able to see numbers in the ComboBox. No type names.


If you use theme in your application and has something like

<ResourceDictionary Source="WhistlerBlue.xaml" />

in your App.xaml, try to overwrite the item style of the combo box by adding

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ComboBox.ItemContainerStyle>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜