WPF XAML ListBox 绑定到数组

WPF XAML ListBox bind to array

所以我有一个浮点数组,我想将其作为 ListBox 中的 ItemSource。
在 ItemTemplate 内部我有一个进度条,应该将其 Progress 值绑定到给定的 float 值。然而,我永远看不到这些值实际上与进度 属性 绑定。

xaml 代码(我不知道我是否错了,但我预计存在从 float 到 double 的隐式转换):

<ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" BorderThickness="0">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type sys:Double}">
            <StackPanel>
                <ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center"
                                       HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/>
                <TextBlock Margin="0,3,0,3" HorizontalAlignment="Center" Text="{Binding LastUpdateTime, StringFormat='{}{0:hh:mm:ss tt}', Mode=OneWay}"
                           DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

xmlns:sys="clr-namespace:System;assembly=mscorlib"

和 属性 本身:

public double[] CoreLoads
{
    get { return cpuManagement.ProcessorInfo.LoadPercentages; }
}

注意:我使用的进度条是自定义控件,继承自System.Windows.Controls.Control

问题似乎是数组的值没问题,但是当绑定到 TextBlock 时,值是 0,所以进度条的进度总是 0。所以,我有一个正确的双数组的数据模板?或者我应该换成另一种类型的 collection?

我想您应该在 ViewModel 中创建一个 属性(假设您使用的是 MVVM 模式),它将代表 ListBox 的选定值:

    private double selectedCoreLoad;
    public Double SelectedCoreLoad
    {
        get
        {
            return selectedCoreLoad;
        }
        set
        {
            if (selectedCoreLoad != value)
            {
                selectedCoreLoad = value;
                RaisePropertyChanged("SelectedCoreLoad");
            }
        }
    }

然后,您应该将 ListBox 的选定值绑定到此 属性:

<ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" SelectedValue="{Binding SelectedCoreLoad, Mode=TwoWay}" BorderThickness="0">

<ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding SelectedCoreLoad}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center"
                                       HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/>

UPD

改为使用 ObservableCollection:

private ObservableCollection<Double> coreLoads;
public ObservableCollection<Double> CoreLoads
{
    get { return coreLoads; }
    set
    {
        coreLoads = value;
        RaisePropertyChanged("CoreLoads");
    }
}

所以找到了答案:ListBox 似乎不像 ItemsSource 那样喜欢数组。将源更改为双重列表后,一切正常。

public List<double> CoreLoads
{
    get { return new List<double>(cpuManagement.ProcessorInfo.LoadPercentages); }
}