gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:00 25 4
gpt4 key购买 nike

我正在努力寻找为什么我的 SelectedValuePath 没有导致我的组合框将 double 值传递到我的 View 模型属性 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]].

是否因为我相信我正确地遵循了文档而遗漏了一些简单的东西?

窗口.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;
}

最佳答案

SelectedValuePath 不能与 SelectedItem 一起使用。您必须使用 SelectedValue

来自 MSDN 的自定义摘要:

The SelectedValuePath property provides a way to specify a SelectedValue for the SelectedItem. The SelectedItem represents an object in the Items collection and Control displays the value of a single property of the selected item. The SelectedValuePath property specifies the path to the property that is used to determine the value of the SelectedValue property.

关于c# - 为什么我的 comboBox 的 SelectedValuePath 属性行为不正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49303728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com