调用IValueConverter';s ConvertBack已加载

本文关键字:ConvertBack 加载 IValueConverter 调用 | 更新日期: 2023-09-27 18:00:05

I将组合框(即listbox项模板的一部分)绑定到enum,所选项将绑定到绑定到listbox的集合
我用转换器做一些逻辑运算。

问题是ConvertBack不会在启动时调用,而是只有在我重新选择组合框中的项目时才会调用。

我也需要它在启动时调用。

public enum FullEnum 
    {
       Apple,
       Banana,
       Pear
    }
<Window.Resources>
   <local:EnumConverter x:Key="enumConverter"/>
   <ObjectDataProvider x:Key="DataT"
                       MethodName="GetValues" 
                       ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:FullEnum" />
            </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>
<Grid>
   <Grid.RowDefinitions>
        <RowDefinition Height="190*" />
       <RowDefinition Height="71*" />
   </Grid.RowDefinitions>
   <ListBox Name="list1" Margin="0,0,0,37">
        <ListBox.ItemTemplate>
           <DataTemplate>
             <StackPanel>
               <TextBlock Text="{Binding Path=Label}"></TextBlock>
               <ComboBox Height="23" Width="90"                                 
                         ItemsSource="{Binding Source={StaticResource DataT}}"                                                                  
                         SelectedValue="{Binding Path=Oped, Converter={StaticResource enumConverter}}">
                </ComboBox>
             </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
  </Grid>
List<Item1> list = new List<Item1>();
public Window1()
{
     InitializeComponent();
     list.Add(new Item1 { Label="label1" });
     list.Add(new Item1 { Label = "label2" });
     list.Add(new Item1 {  Label = "label3" });
     list1.ItemsSource = list;
}
    public class Item1
    {
            public FullEnum Oped { get; set; }
            public string Label { get; set; }
    }
 public class EnumConverterr : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //some code        
        }
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((int)value != 0)
            return (EnumSuperior)value;
        return (EnumSuperior)7;
    }
    }

调用IValueConverter';s ConvertBack已加载

WPF在初始化时不会调用返回转换器,因为它刚刚从数据上下文中获得初始值。数据绑定的源和目标应该具有相同的值,因此没有理由更新源。

您还没有发布转换回逻辑,但转换器中必须有一些"状态完整"的逻辑。转换器应该是无状态的(没有副作用,不可变)。所有转换都应基于在转换过程中未修改的值、参数和转换器属性。

如果您的转换器是无状态的,那么您所需要做的就是正确地初始化数据源,并且不再需要初始的convert-back调用。