WPF ComboBox ItemTemplate Binding 更新问题
程序运行起来第一次能执行到enumDescriptionConverter,如果用户点击OK按钮之后怎样才能再次触发Converter,以下是xaml和CS代码。
<ComboBox Width="200" Height="50" Margin="100"
HorizontalAlignment="Center"
VerticalAlignment="Center"
ItemsSource="{Binding AlarmLevelList, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedAlarmLevel}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Content="OK" Width="100" Height="30" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Click"/>
public enum AlarmLevel
{
[Description("正常")]
Normal = 0,
[Description("警报")]
Warring = 1,
[Description("故障")]
Error = 2,
}
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
InitList();
}
public List<AlarmLevel> AlarmLevelList
{
get
{
return _alarmLevelList;
}
set
{
_alarmLevelList = value;
DoPropertyChanged(AlarmLevelListPropertyName);
}
}
private List<AlarmLevel> _alarmLevelList;
public const string AlarmLevelListPropertyName = "AlarmLevelList";
public AlarmLevel SelectedAlarmLevel
{
get { return _selectedAlarmLevel; }
set
{
if (_selectedAlarmLevel != value)
{
_selectedAlarmLevel = value;
DoPropertyChanged(SelectedAlarmLevelPropertyName);
}
}
}
private AlarmLevel _selectedAlarmLevel;
public const string SelectedAlarmLevelPropertyName = "SelectedAlarmLevel";
public void InitList()
{
AlarmLevelList = new List<AlarmLevel>();
AlarmLevelList.Add(AlarmLevel.Normal);
AlarmLevelList.Add(AlarmLevel.Warring);
AlarmLevelList.Add(AlarmLevel.Error);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DoPropertyChanged(AlarmLevelListPropertyName);
DoPropertyChanged(SelectedAlarmLevelPropertyName);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void DoPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class EnumDescriptionConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value as string != "")
{
Enum myEnum = (Enum)value;
string description = GetEnumDescription(myEnum);
return description;
}
return "";
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Empty;
}
private string GetEnumDescription(Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
{
return enumObj.ToString();
}
else
{
DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
}