2017-08-17 90 views
0

我創建了一個ComboBox和綁定系統枚舉衣被合計到它。並且還爲它創建了一個值轉換器,使其更具人性化。 但是,當我選擇ComboBox中的項目時,它顯示錯誤並在控制檯中轉儲了一些錯誤消息 任何想法如何解決該問題? 我也嘗試爲SelectedItem設置另一個值轉換器,但它也不起作用。的IValueConverter與枚舉convertback失敗

CS文件:

using System; 
using System.Collections.Generic; 
using System.Globalization; 
using System.IO.Ports; 
using System.Linq; 
using System.Windows; 
using System.Windows.Data; 

namespace WpfApp1 
{ 
    public partial class MainWindow : Window 
    { 
     private StopBits _stopBits; 

     public StopBits SelectedStopBits 
     { 
      get { return _stopBits; } 
      set { _stopBits = value; } 
     } 

     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = this; 
     } 
    } 

    public class DataConvert : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      var tmp = (int[])value; 
      var convert = new Dictionary<StopBits, string>() 
      { 
       {StopBits.None, "none"}, 
       {StopBits.One, "1 bit"}, 
       {StopBits.Two, "2 bit"}, 
       {StopBits.OnePointFive, "1.5 bit"} 
      }; 

      return tmp.Select(item => convert[(StopBits)item]).ToList(); 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      return value; 
     } 
    } 
} 

XAML文件:

<Window x:Class="WpfApp1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApp1" 
     xmlns:serialPort="clr-namespace:System.IO.Ports;assembly=System" 
     xmlns:provider="clr-namespace:System;assembly=mscorlib" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <ObjectDataProvider x:Key="StopBitsProvider" MethodName="GetValues" ObjectType="{x:Type provider:Enum}"> 
      <ObjectDataProvider.MethodParameters> 
       <x:Type TypeName="serialPort:StopBits"/> 
      </ObjectDataProvider.MethodParameters> 
     </ObjectDataProvider> 
     <local:DataConvert x:Key="DataConverter"/> 
    </Window.Resources> 
    <StackPanel> 
     <TextBlock Text="Stop Bits:"/> 
     <ComboBox ItemsSource="{Binding Source={StaticResource StopBitsProvider}, Converter={StaticResource DataConverter}}" 
        SelectedItem="{Binding SelectedStopBits}"/> 
    </StackPanel> 
</Window> 

錯誤:

System.Windows.Data Error: 7 : ConvertBack cannot convert value '2 bit' (type 'String'). 
BindingExpression:Path=SelectedStopBits; DataItem='MainWindow' (Name=''); target element is 'ComboBox' (Name=''); 
target property is 'SelectedItem' (type 'Object') FormatException:'System.FormatException: 2 bit is not valid StopBits value 
System.Enum.EnumResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument) 
System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) 
System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) 
System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) 
System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) 
MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) 
MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture) 
System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)' 
+1

你可以用綁定的單向的SelectedItem(只有數據> GUI)和帶OneWayToSource的SelectedIndex(僅GUI>數據)。 – CShark

+0

我試過了,效果很好。感謝您的幫助 – Archer

回答

1

您需要的SelectedItemstring轉換爲StopBits值。

這樣就適用於SelectedItem結合應該返回枚舉值的源屬性實際上可以設置轉換器的ConvertBack方法:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    StopBits enumValue = default(StopBits); 
    if (value != null) 
     Enum.TryParse(value.ToString(), out enumValue); 

    return enumValue; 
} 

你不能設置一個StopBits屬性添加到string

編輯:或者你可以只返回字典從轉換器:

public class DataConvert : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var tmp = (int[])value; 
     var convert = new Dictionary<StopBits, string>() 
     { 
      {StopBits.None, "none"}, 
      {StopBits.One, "1 bit"}, 
      {StopBits.Two, "2 bit"}, 
      {StopBits.OnePointFive, "1.5 bit"} 
     }; 

     return convert; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value; 
    } 
} 

...修改您的XAML一點:

<ComboBox ItemsSource="{Binding Source={StaticResource StopBitsProvider}, Converter={StaticResource DataConverter}}" 
      SelectedValuePath="Key" 
      DisplayMemberPath="Value" 
      SelectedValue="{Binding SelectedStopBits}"/> 
+0

真的非常感謝您的幫助。它困擾了一陣子。 – Archer