当我向ComboBox.ItemTemplate添加图标时,我有一种奇怪的行为。 在最初加载项目后,所有项目都显示相应的图标,但是当我选择一个项目时,图标将显示在组合部分中,但将在Expander Part中消失。
You can see the problem here (imgur)
我对WPF / C#没有经验,我绑定项目或ComboBox.ItemTemplate的方式有问题吗?
非常感谢您的帮助.-
XAML代码
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Height="32" Margin="60,47,0,0" VerticalAlignment="Top" Width="282" ItemsSource="{Binding OtherTasks}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0" Height="30">
<ContentControl Content="{Binding Path=Icono}" Margin="0,4,0,0" Background="Yellow" Width="16" Height="16" Visibility="Visible"/>
<AccessText HorizontalAlignment="Stretch" Margin="3,4,0,0" Text="{Binding Path=Text}" TextAlignment="Left" Width="Auto" />
</DockPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
CS代码
namespace test___icon {
public partial class MainWindow : MetroWindow {
public class CLASS_OTHERTASKS {
public string Text { get; set; }
public object Icono { get; set; }
}
public List<CLASS_OTHERTASKS> OtherTasks { get; set; }
public MainWindow() {
OtherTasks = new List<CLASS_OTHERTASKS>();
OtherTasks.Add(new CLASS_OTHERTASKS() { Text = "Test Air", Icono = new PackIconEntypo() { Kind = PackIconEntypoKind.Air } });
OtherTasks.Add(new CLASS_OTHERTASKS() { Text = "Test Account", Icono = new PackIconMaterial() { Kind = PackIconMaterialKind.Account } });
OtherTasks.Add(new CLASS_OTHERTASKS() { Text = "Test AxisThree", Icono = new PackIconModern() { Kind = PackIconModernKind.AxisThree } });
InitializeComponent();
this.DataContext = this;
}
}
}
答案 0 :(得分:0)
控件只能在可视化树中出现一次,因此从数据绑定属性返回控件并不是一个好主意。您最好在XAML标记中定义可视控件。像这样:
<ComboBox x:Name="comboBox" ItemsSource="{Binding OtherTasks}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0" Height="30">
<ContentControl x:Shared="False" Content="{Binding}" Margin="0,4,0,0" Background="Yellow" Width="16" Height="16" Visibility="Visible">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding Text}" Value="Test Air">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<iconPacks:PackIconEntypo Kind="Air" />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Text}" Value="Test Account">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<iconPacks:PackIconMaterial Kind="Account" />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Text}" Value="Test AxisThree">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<iconPacks:PackIconModern Kind="AxisThree" />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
<AccessText HorizontalAlignment="Stretch" Margin="3,4,0,0" Text="{Binding Path=Text}" TextAlignment="Left" Width="Auto" />
</DockPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>