我有一个组合框,其中的项目来源来自ObservableCollection
listSites = new ObservableCollection<SiteData>()
{
new SiteData("Site 1", true, "HomeAutomation", "Green"),
new SiteData("Site 2", true, "HomeAutomation", "Green"),
new SiteData("Site 3", true, "HomeAutomation", "Green"),
new SiteData("Site 4", false, "HomeAlert", "Red"),
new SiteData("Site 5", true, "HomeAutomation", "Green"),
new SiteData("Site 6", true, "HomeAutomation", "Green"),
new SiteData("Site 7", true, "HomeAutomation", "Green"),
new SiteData("Site 8", false, "HomeAlert", "Red"),
new SiteData("Site 9", true, "HomeAutomation", "Green"),
new SiteData("Site 10", false, "HomeAlert", "Red"),
};
cbxSites.ItemsSource = listSites;
组合框还具有一个用于StaticResource的ItemTemplate:
<ComboBox x:Name="cbxSites" VerticalAlignment="Top" Width="250" Margin="0,
0, 0, 0" BorderBrush="White"
ItemsSource="{Binding listSites}" ItemTemplate="
{StaticResource SiteComboBoxItemTemplate}"
HorizontalContentAlignment="Center"
SelectionChanged="CbxSites_SelectionChanged"
IsEditable="True" />
<DataTemplate x:Key="SiteComboBoxItemTemplate">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<materialDesign:PackIcon Kind="{Binding StatusIcon}"
Width="30" Height="30" Foreground="{Binding StatusColour}"
VerticalAlignment="Center" HorizontalAlignment="Right" />
<TextBlock Text="{Binding SiteName}" Margin="20, 0, 0, 0" />
</StackPanel>
</DataTemplate>
将ComboBox上的IsEditable设置为false时,绑定起作用,我可以单击Combobox并查看所有名称(站点1,站点2,站点3等),然后单击一个项目,它会填充相同的名称如您所愿,在“组合框”中命名。当IsEditable为true时,组合框的下拉列表仍会正确显示站点名称(站点1,站点2,站点3等),但是当我选择一个站点时,而不是在组合框中填充的该站点的相同名称改为使用“ CipClient.SiteData”。为什么会这样,我该如何解决?
答案 0 :(得分:0)
WPF IsEditable = true填充有对象的组合框会将ToString()显示为选定项。 您可以解决此问题:
<ComboBox x:Name="cbxSites" VerticalAlignment="Top" Width="250" Margin="0, 0, 0, 0" BorderBrush="White"
ItemsSource="{Binding listSites}" IsTextSearchEnabled="True" TextSearch.TextPath="SiteName" ItemTemplate="{StaticResource SiteComboBoxItemTemplate}" HorizontalContentAlignment="Center" SelectionChanged="CbxSites_SelectionChanged"
IsEditable="true" />