2013-08-17 39 views
0

我想绑定组合框的选择更改以更新我的列表框,但是我的xaml代码可能是错误的。将ListBox绑定到XAML中的SelectionChanged组合框

这是我的服务收集数据。

public class WorkersCollection 
{ 
    private WorkerClient client = new WorkerClient(); 
    public ObservableCollection<Worker> Workers { get; set; } 

    public WorkersCollection() 
    { 
     Workers = new ObservableCollection<Worker>(); 
    } 

    public ICollection<Worker> GetAllWorkers() 
    { 
     foreach (var worker in client.GetAllWorkers()) 
     { 
      Workers.Add(worker); 
     } 

     return Workers; 
    } 
} 

我的DataContext是工人:

public partial class MainWindow : Window 
{ 
    WorkersCollection workers; 

    public MainWindow() 
    { 
     InitializeComponent(); 

     workers = new WorkersCollection(); 
     this.DataContext = workers; 

     workers.GetAllWorkers(); 
    } 
} 

和XAML:

<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <ComboBoxItem Content="{Binding LastName}" /> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem}" /> 

我怎样才能解决呢?

+0

改变方式? 'Combobox'和'ListBox'之间的关系是什么?什么是'工人'级?目前'ListBox'上的'ItemsSource'从'ComboBox'中选择'Worker'。这是一个列表吗? – dkozl

回答

1

ItemsSource 类别的属性具有类型IEnumerablemsdn)。

所以你不能指定它Worker类型的对象。

你可以创建转换器来做到这一点。

Converter类:

public class WorkerToListConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return new List<Worker> { value as Worker }; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

XAML代码:

... 
<Window.Resources> 
     <local:WorkerToListConverter x:Key="myCon" /> 
</Window.Resources>  
... 
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" ItemsSource="{Binding Workers}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <ComboBoxItem Content="{Binding LastName}" /> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" 
     ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem, Converter={StaticResource myCon}}" /> 
... 

你也应该删除SelectedItem从组合框结合。

... SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}" ... 

这是没有意义的结合SelectedItem以同样的事情ItemsSource

+0

现在它工作:) –