我有一个绑定到枚举的组合框,工作正常,但当我使用IValueConverter
使枚举值更友好时,组合框中不再有默认的选定项。有什么想法吗?
[ValueConversion(typeof(InstallerAction), typeof(string))]
public class InstallerActionConverter : IValueConverter
{
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var installerActions = (InstallerAction[])value;
var result = new List<string>();
foreach(var item in installerActions)
{
switch (item)
{
case InstallerAction.Install:
result.Add("Install");
break;
case InstallerAction.None:
result.Add("None");
break;
case InstallerAction.UninstallAll:
result.Add("Uninstall All");
break;
case InstallerAction.UninstallOne:
result.Add("Uninstall One");
break;
}
}
return result;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var installerActions = (string)value;
switch (installerActions)
{
case "None":
return InstallerAction.None;
case "Install":
return InstallerAction.Install;
case "Uninstall One":
return InstallerAction.UninstallOne;
case "Uninstall All":
return InstallerAction.UninstallAll;
default:
return InstallerAction.None;
}
}
}
和XAML:
<ListView Name="ListView" ItemsSource="{Binding DatabaseInfos}" VerticalAlignment="Stretch" Margin="10">
<ListView.Resources>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Action">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Width="100" ItemsSource="{Binding Source={StaticResource ActionFromEnum}, Converter={StaticResource InstallerActionConverter}}" SelectedItem="{Binding Action}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
...
答案 0 :(得分:1)
将Converter转换为您的SelectedItem绑定。
答案 1 :(得分:0)
而不是使用转换器来绑定项目源,然后选择项目, 您可以尝试仅为组合框项目设置项目模板,以显示友好名称。