如何在每个wpf/MVVM combox行上显示2个字符串

本文关键字:combox 显示 字符串 2个 MVVM wpf | 更新日期: 2023-09-27 17:51:17

编辑:这实际上适用于两种情况,但回溯更改并不能帮助我找到真正的问题。所以模板不是问题的根源。

每一行都有一个类:

public class OptionItem
{
    public int Id { get; set; }
    public string Label { get; set; }
    public string BitMap { get; set; }
}

现在当我的XAML像下面一样一切正常(显示标签):

<ComboBox Grid.Row="0" Grid.Column="0" Name="OptionsComboBox" ItemsSource="{Binding Path=OptionsItemsSource}" DisplayMemberPath="Label" SelectedItem="{Binding Path=SelectedOptionItem, Mode=TwoWay}" />

但是当我尝试(错误地)使用ItemTemplate时,组合框是空的(ItemsSource的get-accessor被正常调用并且有项):

<ComboBox Grid.Row="0" Grid.Column="0" Name="OptionsComboBox" ItemsSource="{Binding Path=OptionsItemsSource}" SelectedItem="{Binding Path=SelectedOptionItem, Mode=TwoWay}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <WrapPanel>
                    <TextBlock Text="{Binding Path=Label}"/>
                    <TextBlock Text="{Binding Path=BitMap}"/>
                </WrapPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

其余的东西在下面。我知道我使用了我们自己的类,这里没有解释,但我想强调的是,组合框没有模板(虽然只有1个字符串),所以这些不应该太有趣。

ViewModel中所选项的属性:

    private OptionItem _selectedOptionItem;
    public OptionItem SelectedOptionItem
    {
        get { return _selectedOptionItem; }
        set
        {
            // to raise property changed
            SetValue(ref _selectedOptionItem, value);
        }
    }

和itemssource在ViewModel:

    private ItemsSource<OptionItem> _optionsItemsSource;
    public ItemsSource<OptionItem> OptionsItemsSource
    {
        get { return _optionsItemsSource; }
        private set
        {
            // to raise property changed
            SetValue(ref _optionsItemsSource, value);
        }
    }

如何在每个wpf/MVVM combox行上显示2个字符串

ItemTemplate中使用WrapPanel时可能无法正常工作。尝试使用水平的StackPanel代替:

<DataTemplate>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=Label}"/>
        <TextBlock Text="{Binding Path=BitMap}"/>
    </StackPanel>
</DataTemplate>

WrapPanel for me:

    <ComboBox DockPanel.Dock="Left" Width="100" ItemsSource="{Binding StudentList}" SelectedItem="{Binding SelectedStudent}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <WrapPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text=", " />
                    <TextBlock Text="{Binding Age}" />
                </WrapPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

我的ItemsSource是一个ObservableCollection,然而:

    public ObservableCollection<StudentViewModel> StudentList
    {
        get { return _studentList; }
        private set { _studentList = value; }
    }