XAML AlternationIndex未显示在组合框中

b4lqfgs4  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(125)

下拉列表中显示了索引和值,但组合框中只显示了值,下拉列表关闭后如何显示索引?

<ComboBox ItemsSource="{Binding DoubleList}" AlternationCount="{x:Static system:Int32.MaxValue}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Run Text="{Binding (ItemsControl.AlternationIndex), Mode=OneWay, RelativeSource={RelativeSource AncestorType=ComboBoxItem}, StringFormat={}{0} :"/>
                <Run Text="{Binding ., StringFormat={}{0:F4}}"/>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
qyuhtwio

qyuhtwio1#

ComboBox关闭时,可视树中不存在ComboBoxItem,因此当前绑定到(不存在的)父级ComboBoxItemItemsControl.AlternationIndex attached属性的解决方案将不起作用。
您应该将DoubleList的类型从IEnumerable<double>更改为IEnumerable<T>,其中T是一个视图模型,具有存储项索引的属性:

public class Item : INotifyPropertyChanged
{
    private int _index;
    public int Index
    {
        get { return _index; }
        set { _index = value; NotifyPropertyChanged(); }
    }

    private double _value;
    public double Value
    {
        get { return _value; }
        set { _value = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
...
public IEnumerable<Item> DoubleList { get; }

然后,您必须以某种方式设置它,例如使用视图中的事件处理程序:

private void ComboBoxItem_Loaded(object sender, RoutedEventArgs e)
{
    ComboBoxItem comboBoxItem = (ComboBoxItem)sender;
    Item item = comboBoxItem.DataContext as Item;
    if (item != null)
        item.Index = ItemsControl.GetAlternationIndex(comboBoxItem);
}

XAML文件:

<ComboBox ItemsSource="{Binding DoubleList}" AlternationCount="{x:Static system:Int32.MaxValue}">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <EventSetter Event="Loaded" Handler="ComboBoxItem_Loaded" />
        </Style>
    </ComboBox.ItemContainerStyle>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Run Text="{Binding Index, Mode=OneWay, StringFormat={}{0} :}"/>
                <Run Text="{Binding Value, StringFormat={}{0:F4}}"/>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

这是MVVM的一个简单例子,视图通过编程方式设置视图模型的属性就像通过XAML标记中的绑定一样简单(在这个特定的例子中是不可能的)。

相关问题