Reputation: 196
I'm struggling to find why my SelectedValuePath
isn't causing my combo box to pass a double to my view model property DelayLength
. When I change the combo box selection during execution the combobox turns red and gives the error :
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]].
Is there something simple I'm missing because I believe I'm following documentation correctly?
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;
}
Upvotes: 3
Views: 1032
Reputation: 4046
SelectedValuePath
can not be used with SelectedItem
. You have to use SelectedValue
.
Customized summary from 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.
Upvotes: 3