2015-10-15 125 views
0

在以下xaml片段中,SessoList是一个字符串列表(“M”和“F”)。带数据绑定的Wpf组合框:初始值为空

<ComboBox IsEditable="False" Margin="5" SelectedValue="{Binding Sesso}" ItemsSource="{Binding SessoList}" Width="40" Height="28"/> 

组合框按预期方式工作,这是预填充反射Sesso在视图模型的值。

组合框可选项目只有两种固定所以我试图简化在XAML定义它们:

<ComboBox IsEditable="False" Margin="5" SelectedValue="{Binding Sesso}" SelectedValuePath="{Binding Tag}" Width="40" Height="28" Name="Primo"> 
      <ComboBoxItem Content="M" Tag="M" /> 
      <ComboBoxItem Content="F" Tag="F" /> 
     </ComboBox> 

此组合框是能够更新的视图模型属性sesso的,但没有预先填充了正确值。报道

以下错误:

BindingExpression path error: 'Tag' property not found on 'object' 

我怎样才能成功地定义在XAML组合框中的项目,并将它显示基于的SelectedValue绑定正确的价值?

忘了提我使用.NET 4.0

回答

0

至于我能理解,你想在XAML来定义组合框的ItemsSource, 这里是为我工作的解决方案:

  1. XAML窗口资源:

    <Window.Resources> 
    <x:Array x:Key="Array" Type="{x:Type nirHelpingOvalButton:ComboObjectModel}"> 
        <nirHelpingOvalButton:ComboObjectModel Content="M_Content" Tag="M_Tag"/> 
        <nirHelpingOvalButton:ComboObjectModel Content="F_Content" Tag="F_Tag"/> 
    </x:Array> 
    

  2. 的XAML组合:

    <Grid> 
    <ComboBox IsSynchronizedWithCurrentItem="True" IsEditable="False" SelectedIndex="0" Margin="5" ItemsSource="{StaticResource Array}" 
          SelectedValue="{Binding Content, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
          SelectedValuePath="Tag" Width="90" Height="28" Name="Primo"> 
        <i:Interaction.Behaviors> 
         <nirHelpingOvalButton:CustomComboSelectionBehavior/> 
        </i:Interaction.Behaviors> 
        <ComboBox.ItemTemplate> 
         <DataTemplate> 
          <TextBlock Text="{Binding Content}"></TextBlock> 
         </DataTemplate> 
        </ComboBox.ItemTemplate> 
    </ComboBox></Grid> 
    
  3. 视图模型组合的SelectedValue绑定属性:

    public string Content 
    { 
        get { return _content; } 
        set 
        { 
         _content = value; 
         OnPropertyChanged("Content"); 
        } 
    } 
    
  4. 列表项行为的代码:

    protected override void OnAttached() 
    { 
        base.OnAttached(); 
        AssociatedObject.Loaded += OnLoaded; 
    } 
    
    private void OnLoaded(object sender, RoutedEventArgs e) 
    { 
        var firstItem = AssociatedObject.ItemsSource.Cast<object>().FirstOrDefault(); 
        AssociatedObject.SelectedItem = firstItem; 
    } 
    
    protected override void OnDetaching() 
    { 
        base.OnDetaching(); 
        AssociatedObject.Loaded -= OnLoaded; 
    } 
    

问候

+0

有没有必要定义资源数组,comboboxitem方法也运作良好。比较组合框的定义,我在代码中发现了错误:** SelectedValuePath =“{Binding Tag}”**是错误的,用** SelectedValuePath =“Tag”代替**行为是好的 – Filippo