【问题标题】:How to fill a ComboBox with indexes of bound collection?如何用绑定集合的索引填充组合框?
【发布时间】:2022-01-08 13:55:26
【问题描述】:

我想创建一个ComboBox,其内容为“Sample 01”中的TextBlocks,其中数字被替换为项目的索引(从1开始)。

下面大致是我目前的代码:

<ComboBox
    x:Name="ComboSampleItems"
    Grid.Column="0"
    Height="20"
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding ReportModel.SampleData}"
    SelectedItem="{Binding SelectedSampleScans}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ????, StringFormat=Something here?}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我使用INPC 来确保VM 上的更改反映视图,因为我使用的是MVVM。 我怎样才能达到我想要的结果?我考虑过转换器,但不确定它是否适合我想做的事情,或者是否有更好的方法。

这是否与this topic? 有关系

【问题讨论】:

    标签: c# wpf xaml data-binding combobox


    【解决方案1】:

    集合不为其项目提供显式索引。换句话说,虽然例如List&lt;string&gt; 包含字符串并且它们都可以被索引,单个项目的索引没有属性。您可以做的只是公开 (Index, Item) 元组的集合。注意,我在这里使用Tuple&lt;string, int&gt;,因为像(string, int)are not bindable这样的值元组。您也可以构造自定义类型或改用KeyValuePair&lt;string, int&gt;

    public List<Tuple<string, int>> IndexedSampleData { get; }
    

    您可以使用 LINQ 及其Select 方法对其进行初始化。根据您的具体情况,您不妨为此使用IEnumerable&lt;(string, int)&gt;ObservableCollection&lt;(string, int)&gt;

    IndexedSampleData = SampleData.Select((item, index) => new Tuple<string, int>(item, index)).ToList();
    

    在 XAML 中,您可以将MultiBindingStringFormat 结合使用,请参阅Standard numeric format strings。使用属性Item1Item2 引用元组组件。

    <ComboBox
       x:Name="ComboSampleItems"
       Grid.Column="0"
       Height="20"
       HorizontalAlignment="Stretch"
       ItemsSource="{Binding IndexedSampleData}">
       <ComboBox.ItemTemplate>
          <DataTemplate>
             <TextBlock>
                <TextBlock.Text>
                   <MultiBinding StringFormat="{}{0} {1:D2}">
                      <Binding Path="Item1"/>
                      <Binding Path="Item2"/>
                   </MultiBinding>
                </TextBlock.Text>
             </TextBlock>
          </DataTemplate>
       </ComboBox.ItemTemplate>
    </ComboBox>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 2019-06-11
      • 2019-09-12
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多