WPF Combobox 附加 属性 用于 selectionchange 未触发

WPF Combo box attached property for slection change not firing

为了触发列表框选择更改,我创建了一个附加的 属性 并将其绑定到我的 XAML,如下所示,

<Controls:MetroWindow x:Class="Transport.MainWindow"
          xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        xmlns:extension="clr-namespace:Transport.Extensions"
        xmlns:local="clr-namespace:Transport
        mc:Ignorable="d"
        Title="CIP Simulator" Height="550" Width="1500"
                      BorderThickness="0" 
                      GlowBrush="Black"
                      ResizeMode="CanResizeWithGrip"
                      ShowMaxRestoreButton="False"
                      WindowTransitionsEnabled="False"
                      WindowStartupLocation="CenterScreen">
 <ComboBox Grid.Column="1" Grid.Row="2" ItemsSource="{Binding Sets}" DisplayMemberPath="Set" 
                  extension:CommandProviders.Command="{Binding SetSelectionChange}"
                  SelectedItem="{Binding SelectedSet}" Grid.ColumnSpan="3"/>

现在附加的 属性 def 如下所示:

public class CommandProviders
    {
        public static ICommand GetCommand(DependencyObject depObject)
        {
            return (ICommand)depObject.GetValue(CommandProprtey);
        }

        public static void SetCommand(DependencyObject depobject, ICommand value)
        {
            depobject.SetValue(CommandProprtey, value);
        }

        public static readonly DependencyProperty CommandProprtey =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandProviders), null);
    }

我现在已经创建了 public I 命令并分配给 relayCommand(这是其他按钮的工作中继命令)。

 public ICommand SetSelectionChange { get; set; }
 SetSelectionChange = new RelayCommand(commandx =>
                {
                    //Do Something

                });

但这并没有启动选择更改!!

如评论中所述,您应该定义PropertyChangedCallback。下面是订阅 combBox Selection Changed 并引发应触发绑定 RelayCommand.

的命令的管道代码
public class CommandProviders
{
    public static ICommand GetCommand(DependencyObject depObject)
    {
        return (ICommand)depObject.GetValue(CommandProprtey);
    }

    public static void SetCommand(DependencyObject depobject, ICommand value)
    {
        depobject.SetValue(CommandProprtey, value);
    }

    public static readonly DependencyProperty CommandProprtey =
        DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandProviders), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));

}


private static void OnCommandChanged
(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ComboBox cmbBox= (ComboBox)d;
    if (cmbBox != null)     
    {
        cmbBox.SelectionChanged += (sender, eventArgs) => 
           {
               d.GetValue(CommandProprtey)?.Invoke(null);
           }
    }
}

其他几点

为您的示例视角编写此代码。在代码中,SelectionChanged 事件已订阅,因此您必须了解如何取消订阅该事件,以免导致内存泄漏。