Getting selected item in ItemsControl

后端 未结 2 1946
遥遥无期
遥遥无期 2021-02-13 15:18

I have the following code which populates my user control in form of rows and column. The user control which is being populated contains Button, links, textbox etc. When a certa

2条回答
  •  余生分开走
    2021-02-13 15:33

    I have a solution for you...a behavior:

       public static class SelectedItemBehavior
       {
          public static readonly DependencyProperty BindingProperty =
             DependencyProperty.RegisterAttached("Binding", typeof(object), typeof(SelectedItemBehavior),
                new FrameworkPropertyMetadata(new object(),
                   FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                   SelectedItem_Changed));
    
          public static object GetBinding(FrameworkElement frameworkElement)
          {
             return (object)frameworkElement.GetValue(BindingProperty);
          }
    
          public static void SetBinding(FrameworkElement frameworkElement, object value)
          {
             frameworkElement.SetValue(BindingProperty, value);
          }
    
          private static void SelectedItem_Changed(Object sender, DependencyPropertyChangedEventArgs e)
          {
             ToggleButton toggleButton = (ToggleButton)sender;
             toggleButton.Checked -= ToggleButtonOnChecked;
             toggleButton.IsChecked = e.NewValue?.Equals(toggleButton.DataContext) ?? false;
             toggleButton.Checked += ToggleButtonOnChecked;
          }
    
          private static void ToggleButtonOnChecked(object sender, RoutedEventArgs e)
          {
             ToggleButton toggleButton = (ToggleButton)sender;
             SetBinding(toggleButton, toggleButton.DataContext);
          }
       }
    

    Then bind as follows:

        
            
                
                    
                
            
        
    

提交回复
热议问题