Binding to CurrentItem in a ItemsControl

前端 未结 2 579
难免孤独
难免孤独 2021-01-20 07:32

The XAML below is basically trying to make a list of Buttons (rendered from the Name property of objects in the Views collection in th

相关标签:
2条回答
  • 2021-01-20 08:02

    I think you have to do it manually in code-behind.

    XAML

    <Button Click="ViewListButton_Click">
        <TextBlock Text="{Binding Path=Name}" Name="txtButtonLabel" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/>
    </Button>
    

    Code-behind

    private void ViewListButton_Click(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        ICollectionView view = CollectionViewSource.GetDefaultView(ViewList.ItemsSource);
        view.MoveCurrentTo(button.DataContext);
    }
    

    If you're using the MVVM pattern and/or you don't want to use code-behind, you could bind the button's Command to a command in your ViewModel, as suggested by Will

    0 讨论(0)
  • 2021-01-20 08:19

    Your button does nothing. Usually your ViewModel would have an ICommand called Select (or something similar) that the Button would be bound against

    Command="{Binding Select, ElementName="root"}"

    and you'd pass the instance to the ICommand that you'd like to select

    CommandParameter="{Binding}"

    It would look something like this (c#/XAML like pseudocode):

    public class MyModel { public string Name {get;set;} }
    
    public class MyViewModel
    {
      public ObservableCollection<MyModel> Models {get;set;}
      public ICommand Select {get;set;}
      /* configure Models and Select etc */
    }
    
    <UserControl DataContext="{StaticResource MyViewModelInstance}" x:Name="root">
    <ItemsControl ItemsSource="{Binding Models}">
      <ItemsControl.ItemTemplate>
        <ItemsPanelTemplate>
          <Button Text="{Binding Name}" 
          Command="{Binding Select, ElementName="root"}"
          CommandParameter="{Binding}"/>
       </ItemsPanelTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
    </UserControl>
    

    The ItemsControl binds to Models, so each MyModel in Models gets a button. The button text is bound to the property Name. The button command is bound to the Select property in the ViewModel. When the button is pressed, it calls the ICommand, sending in the instance of MyModel that the button is bound against.

    Please do note that using ViewModels within a UserControl is a code smell. UserControls should appear to users as all other controls--they should have bindable public properties which are bound to the user's ViewModel, not yours. You then bind to the values of these properties within the UserControl. For this example, you would have an ItemsSource property defined on your UserControl, and the ItemsControl would bind to this property rather than a ViewModel directly.

    0 讨论(0)
提交回复
热议问题