【问题标题】:WPF C# add text and image to ComboBox during runtimeWPF C# 在运行时将文本和图像添加到 ComboBox
【发布时间】:2021-02-20 09:04:58
【问题描述】:

基本上,当用户单击按钮时,我想在ComboBox 中添加当前正在运行的应用程序的名称列表以及它们旁边的图标。我知道如何获取应用程序列表和图标,但不确定如何将所有内容链接在一起。我的ComboBox XAML 目前如下所示:

<ComboBox x:Name="dial1AppSelection" Grid.Column="3" Grid.Row="4" MinHeight="25" Height ="25" MaxHeight="35" MinWidth="120" Margin="4,0,0,0" SelectionChanged="dial1AppSelection_SelectionChanged">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Height="20" Source="???" />
                <TextBlock ><Run Text="???" /></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

【问题讨论】:

    标签: c# wpf xaml combobox


    【解决方案1】:
    1. 添加到您的组合框
        ItemsSource="{Binding YourCollection}"
    
    1. 为您的对象创建类:
        public class MyProcess
        {
            public ImageSource Image { get; set; }
            public string Text { get; set; } 
        }
    
    1. 将此类代码添加到您的 MainWindow.xaml.cs
        public ObservableCollection<MyProcess> YourCollection { get; set; }
        public MainWindow()
        {
            InitializeComponent();
        
            YourCollection = new ObservableCollection<MyProcess>();
            YourCollection.Add(new MyProcess() { Image ="image1", Text = "txt1"});
        
            DataContext = this;
        }
    
    1. 在您的 xaml 代码中插入字段名称:
        Source="{Binding Path=Image}"
    
        Text="{Binding Path=Text}"
    

    【讨论】:

    • 如果 Image var 是位图类型,Image 应该是位图而不是字符串?
    • 这个实现非常适合我。唯一的补充是将我的 bmps 转换为 ImageSource 类型。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多