2009-08-26 46 views
0

我有一類這樣的:XAML:綁定到一個子集在

public class Contest { 
    List<ContestTeam> Teams { get; set; } 
} 

public class ContestTeam { 
    int TeamId { get; set; } 
    int FinalScore { get; set; } 
} 

我的視圖模型是這樣的:

public class ScheduleViewModel { 
    int CurrentTeamId { get; } 
    List<Contest> Schedule { get; } 
} 

我的XAML看起來是這樣的:

<ListBox ItemsSource="{Binding Path=Schedule}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 

      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition /> 
       </Grid.ColumnDefinitions> 
       <Grid.RowDefinitions> 
        <RowDefinition /> 
        <RowDefinition /> 
       </Grid.RowDefinitions> 

       <StackPanel Grid.Row="0" Orientation="Horizontal"> 
        <!-- TODO: DataContext is currently hard coded to 425 - this needs to be fixed --> 
        <StackPanel Orientation="Horizontal" 
          DataContext="{Binding Path=Teams, Converter={StaticResource CurrentTeam}, ConverterParameter=425}"> 

         <TextBlock Text="{Binding SomeProperty}" /> 
        </StackPanel> 

        <Button Content="Delete" /> 
       </StackPanel> 

       <ListBox Grid.Row="1" ItemsSource="{Binding Teams}"> 
        <!-- a list of all the teams --> 
       </ListBox> 
      </Grid> 

     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

本質上,所以我可以繼續開發我創建了一個值轉換器(CurrentTeam)並且硬編碼了TeamId作爲ConverterParameter,所以我可以繼續開發視圖。但是我陷入了僵局。有沒有一種方法(使用XAML)將StackPane l的DataContext綁定到Teams集合中的ContestTeam,該集合的值與ScheduleViewModel.TeamId的值相匹配?

我最後的追索權將只使用Loaded事件StackPanel來設置它在代碼隱藏DataContext,但我想避免這種情況。有沒有任何XAML Ninjas可以幫我解決這個問題?

+0

您可以創建一個'IValueConverter'其派生自'DependencyObject',並有一些'DependencyProperty',它保存'Silverlight'的'Id'。 – Mohsen 2012-10-08 09:19:12

回答

1

無法在XAML綁定中進行查詢。在這種情況下,既然你真的有兩個輸入值(TeamsCurrentTeamId),只需使用一個MultiBindingIMultiValueConverter

public class FindContestByIdConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, 
          object parameter, CultureInfo culture) 
    { 
     var teams = (IEnumerable<ContestTeam>)values[0]; 
     var teamId = (int)values[1]; 
     return teams.Single(t => t.TeamId == teamId); 
    } 

    // ConvertBack that throws NotSupportedException 
    ... 
} 

然後XAML:

<StackPanel> 
    <StackPanel.DataContext> 
    <MultiBinding Converter="{StaticResource FindContestByIdConverter}"> 
     <Binding Path="Teams"/> 
     <Binding Path="CurrentTeamId" /> 
    </MultiBinding> 
    </StackPanel.DataContext> 
    ... 
</StackPanel> 
+0

Silverlight不支持多重綁定 - 但我發現這個鏈接:http://www.scottlogic.co.uk/blog/wpf/2009/06/silverlight-multibindings-how-to-attached-mutiple-bindings-to -a-single-property/ – 2009-08-28 15:46:11

+0

如何實現'ConvertBack' – Mohsen 2012-10-08 10:31:22

+0

對於大多數的多重綁定,真的沒有辦法從最後一個重新創建原來的兩個(或更多)值,所以你只需要拋出NotSupportedException,就是這樣。如果您需要雙向綁定,您需要準確描述您在問題得到解答之前如何工作。 – 2012-10-10 00:06:02