60 lines
2.0 KiB
C#
60 lines
2.0 KiB
C#
using Microsoft.Xaml.Behaviors;
|
|
using System.Windows;
|
|
using System.Windows.Controls;
|
|
using System.Windows.Input;
|
|
|
|
namespace UIShare.Behaviors
|
|
{
|
|
public class TabControlSelectionChangedBehavior : Behavior<TabControl>
|
|
{
|
|
public static readonly DependencyProperty CommandProperty =
|
|
DependencyProperty.Register(
|
|
"Command", typeof(ICommand), typeof(TabControlSelectionChangedBehavior), new PropertyMetadata(null));
|
|
|
|
public static readonly DependencyProperty CommandParameterProperty =
|
|
DependencyProperty.Register(
|
|
"CommandParameter", typeof(object), typeof(TabControlSelectionChangedBehavior), new PropertyMetadata(null));
|
|
|
|
public ICommand Command
|
|
{
|
|
get { return (ICommand)GetValue(CommandProperty); }
|
|
set { SetValue(CommandProperty, value); }
|
|
}
|
|
|
|
public object CommandParameter
|
|
{
|
|
get { return GetValue(CommandParameterProperty); }
|
|
set { SetValue(CommandParameterProperty, value); }
|
|
}
|
|
|
|
protected override void OnAttached()
|
|
{
|
|
base.OnAttached();
|
|
if (AssociatedObject != null)
|
|
{
|
|
AssociatedObject.SelectionChanged += OnSelectionChanged;
|
|
}
|
|
}
|
|
|
|
protected override void OnDetaching()
|
|
{
|
|
if (AssociatedObject != null)
|
|
{
|
|
AssociatedObject.SelectionChanged -= OnSelectionChanged;
|
|
}
|
|
base.OnDetaching();
|
|
}
|
|
|
|
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
|
|
{
|
|
var tabItem = AssociatedObject.SelectedItem as TabItem;
|
|
// 获取选中 TabItem 的 Header
|
|
if (Command != null && Command.CanExecute(tabItem.Header))
|
|
{
|
|
// 使用选中 TabItem 的 Header 作为 CommandParameter
|
|
Command.Execute(((TabItem)AssociatedObject.SelectedItem)?.Header);
|
|
}
|
|
}
|
|
}
|
|
}
|