为什么我的comboBox的SelectedValuePath属性行为不正常?

时间:2018-03-15 15:44:22

标签: c# wpf data-binding

我很难找到为什么我的SelectedValuePath没有导致我的组合框将双精度传递给我的视图模型属性DelayLength。当我在执行期间更改组合框选择时,组合框变为红色并给出错误:

ConvertBack cannot convert value '[2 Seconds, 2]' (type 'KeyValuePair`2'). BindingExpression:Path=DelayLength; DataItem='TestViewModel' (HashCode=62605785); target element is 'ComboBox' (Name=''); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: DoubleConverter cannot convert from System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].

是否有一些简单的遗漏,因为我相信我正确地记录了文档?

Window.xaml     

    <ComboBox Width="120" Height="24" HorizontalAlignment="Left" Margin="5,0"
              DisplayMemberPath="Key"
              SelectedValuePath="Value"
              ItemsSource="{Binding AvailableLengths}"
              SelectedItem="{Binding DelayLength}"/>

    <TextBox Text="{Binding DelayLength, Mode=OneWay}" IsReadOnly="True"></TextBox>

</StackPanel>

Window.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new TestViewModel();
    }
}

TestViewModel.cs

class TestViewModel : GalaSoft.MvvmLight.ViewModelBase
{
    public Collection<KeyValuePair<string, double>> AvailableLengths
    {
        get
        {
            if (_availableLengths == null)
            {
                _availableLengths = new Collection<KeyValuePair<string, double>>()
                {
                    new KeyValuePair<string, double>("None", 0),
                    new KeyValuePair<string, double>("0.5 Seconds", 0.5),
                    new KeyValuePair<string, double>("1 Second", 1),
                    new KeyValuePair<string, double>("2 Seconds", 2),
                    new KeyValuePair<string, double>("3 Seconds", 3)
                };
            }

            return _availableLengths;
        }
    }

    private double _delayLength;

    public double DelayLength
    {
        get { return _delayLength; }
        set
        {
            _delayLength = value;
            RaisePropertyChanged(nameof(DelayLength));
        }
    }

    private Collection<KeyValuePair<string, double>> _availableLengths;
}

1 个答案:

答案 0 :(得分:1)

SelectedValuePath无法与SelectedItem一起使用。您必须使用SelectedValue

来自MSDN的自定义摘要:

  

SelectedValuePath属性提供了一种指定方法   SelectedItem的SelectedValue。 SelectedItem代表一个   Items集合和Control中的对象显示a的值   所选项目的单个属性。 SelectedValuePath属性   指定用于确定值的属性的路径   SelectedValue属性。