2011-06-17 132 views
1

我想要将组合框的选定值绑定到有界对象属性,并且还将每个组合框的选定索引设置为0.
问题是只有第一个组合框显示所选项目。组合框 - 绑定选定的值

public enum SubEnum1 
{  
    Apple=1, 
    Banana=2, 
    Pear=3 
}  

public enum FullEnum 
{  
    Apple=1, 
    Banana=2, 
    Pear=3, 

    Cucumber=4, 
    Tomato=5, 
    Onion=6 
} 

林XAML窗口我有一些数据控制(列表)其中是具有组合框一个DataTemplate。
组合框绑定到SubEnum1。

数据控制是有界的一个对象收集:

List<MyObject> collection = new List<MyObject>() 
//collection.Add... 

mylist.ItemsSource = collection; 

public class MyObject 
{ 
    public FullEnum TheSelectedEnum {get;set;} 
    .... 
    //other properties 
} 



public class EnumConverter2 : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 

      return value; 

     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (value != null) 
       return (FullEnum)value; 

      else return ""; 

     } 
    } 
<ObjectDataProvider x:Key="Enum1" 
        MethodName="GetValues" 
        ObjectType="{x:Type sys:Enum}"> 
      <ObjectDataProvider.MethodParameters> 
       <x:Type TypeName="local:SubEnum1" /> 
      </ObjectDataProvider.MethodParameters> 
</ObjectDataProvider> 

<ListBox Height="261" HorizontalAlignment="Left" Name="mylist" VerticalAlignment="Top" Width="278"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel>    
       <ComboBox Height="23" Width="90"         
         ItemsSource="{Binding Source={StaticResource Enum1}}" 
         SelectedValue="{Binding Path=TheSelectedEnum, Converter={StaticResource enumConverter}}" 
         SelectedIndex="0"/> 
      </StackPanel> 
     </DataTemplate> 
</ListBox.ItemTemplate>  

</ListBox> 

screen (如果我扩大其他组合框我看到的值)

更新到帖子:

也许我可以以某种方式将选定的值传递给绑定的对象?

+0

BTW,你不需要每一个枚举值后添加的号码 - 每一个值是自动比最后一个更大。 当然,将你的第一个值设置为1或任何你喜欢的,但所有其他的将自动跟随。 – DefenestrationDay 2011-06-17 12:53:18

+0

感谢您的提示 – anderi 2011-06-17 13:11:54

回答

1

你可以做到这一点,解决您的问题:

public enum SubEnum1 
{   
    None=0,  
    Apple=1,  
    Banana=2,  
    Pear=3 
} 

然后使用FallbackValue:

<ComboBox Height="23" Width="90" 
    ItemsSource="{Binding Source={StaticResource Enum1}}" 
    SelectedValue="{Binding Path=TheSelectedEnum, FallbackValue=0}" />