0

我将组合框(如果列表框项模板的一部分)绑定到枚举,则选定项绑定到绑定到列表框的集合。
我将转换器用于某些逻辑。

问题是 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;
    }

    }
4

1 回答 1

0

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

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

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

于 2011-06-22T11:51:21.430 回答