WPF组合框附加属性用于选择更改未触发

时间:2018-06-15 05:16:34

标签: c# wpf dependency-properties attached-properties

要激发列表框选择更改,我创建了一个附加属性并将其绑定到我的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(正在为其他按钮执行relay命令)。

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

                });

但这并没有引起选择改变!!

1 个答案:

答案 0 :(得分:2)

如评论中所述,您应该定义PropertyChangedCallback。下面是订阅combBox选择更改的管道代码,并引发应触发绑定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事件,因此您必须查看如何取消订阅事件,以免最终导致内存泄漏。