编辑:这实际上适用于两种情况,但跟踪更改并没有帮助我找到真正的问题。因此,模板不是问题的根源。
我每一行都有一个类:
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>
其余的事情都在下面。我知道我使用的是我们自己的类,这里没有解释,但是我想强调一下,组合框可以在没有模板的情况下工作(尽管只有一个字符串),所以这些应该不会太有趣。
ViewModel中所选项目的属性:
private OptionItem _selectedOptionItem;
public OptionItem SelectedOptionItem
{
get { return _selectedOptionItem; }
set
{
// to raise property changed
SetValue(ref _selectedOptionItem, value);
}
}
和ViewModel中的itemssource:
private ItemsSource<OptionItem> _optionsItemsSource;
public ItemsSource<OptionItem> OptionsItemsSource
{
get { return _optionsItemsSource; }
private set
{
// to raise property changed
SetValue(ref _optionsItemsSource, value);
}
}
最佳答案
在WrapPanel
中使用时,ItemTemplate
可能无法正常工作。尝试使用水平StackPanel
代替:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Label}"/>
<TextBlock Text="{Binding Path=BitMap}"/>
</StackPanel>
</DataTemplate>
关于c# - 如何在每个wpf/MVVM组合框行上显示2个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054180/