【问题标题】:ItemTemplate combox项目模板组合框
【发布时间】:2011-11-18 09:50:57
【问题描述】:

我想在 Windows.UI.Xaml.Controls.ComboxBox 中存储两个 Item。

  1. 将在 ComboBox 中显示的字符串

  2. 不会在组合框中显示的索引

我探索并发现 ItemTemplate 属性可以做到这一点。 有人可以请给我这个样本。

【问题讨论】:

    标签: c# xaml windows-runtime


    【解决方案1】:

    你不需要ItemTemplate,你需要的是这样的:

    combobox.add(new ListItem("string", "index"); 
    

    【讨论】:

    • 如果我这样做,字符串会显示在 Combo 中吗??
    • 组合中只会显示一个值,您可以访问另一个值,例如((ListItem)(cmbWH.SelectedItem)).ShortName/LongName
    • 对不起,我忘了提到它的新组合框。我正在使用 WinRT 组合框。更新了问题。
    【解决方案2】:

    试试这个:

    <UserControl
        x:Class="Application1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DesignHeight="768" 
        d:DesignWidth="1366">
        <Grid 
            x:Name="LayoutRoot" 
            Background="#FF0C0C0C">
            <Rectangle
                x:Name="rect"
                Fill="Black"
                Margin="40,40,0,0" />
    
            <ComboBox
                Margin="40,40,0,0"
                VerticalAlignment="Top"
                HorizontalAlignment="Left"
                ItemsSource="{Binding Items}">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock
                            Text="{Binding Text}" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </Grid>
    </UserControl>
    
    using System.Collections.Generic;
    
    namespace Application1
    {
        partial class MainPage
        {
            public MainPage()
            {
                InitializeComponent();
                this.DataContext = new MainViewModel();
            }
        }
    
        public class MyItem
        {
            public string Text { get; set; }
            public int Id { get; set; }
        }
    
        public class MainViewModel
        {
            public List<MyItem> Items { get; set; }
    
            public MainViewModel()
            {
                this.Items = new List<MyItem>();
                this.Items.Add(new MyItem { Text = "Item 1", Id = 1 });
                this.Items.Add(new MyItem { Text = "Item 2", Id = 2 });
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2021-05-11
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多