【问题标题】:ComboBox - bind selected valueComboBox - 绑定选定的值
【发布时间】:2011-06-17 12:47:10
【问题描述】:

我想将组合框的选定值绑定到有界对象属性,并将每个组合框的选定索引设置为 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 窗口中,我有一些数据控件(列表),其中是具有组合框的数据模板。
组合框绑定到 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>

(如果我展开其他组合框,我会看到值)

更新帖子:

也许我可以通过其他方式将所选值传递给绑定对象?

【问题讨论】:

  • 顺便说一句,您不需要在每个枚举值之后添加数字 - 每个值都会自动比上一个大一。当然,将您的第一个值设置为 1 或任何您喜欢的值,但其他所有值都会自动跟随。

标签: wpf binding enums


【解决方案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}" /> 

【讨论】:

  • 但是将 None=0, 添加到 SubEnum1 将向组合框添加额外的项目。我不需要它。如果出现错误或失败,我想选择第一项并绑定到对象(使用所需的演员表)。我厌倦了使用转换器,但它也不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 2016-03-15
  • 2020-10-10
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
相关资源
最近更新 更多