为什么此附加属性不会更新?

时间:2016-04-12 21:51:59

标签: c# wpf xaml listbox attached-properties

好吧,所以我最初只是将这个问题发布为绑定无效的问题。但是,只要我尝试将代码最小化到SO上,就会产生另一个问题。

因此,基本上,Extensions类用于挂钩ListBox并创建SelectedItems的可绑定版本。抓取SelectedItems并将它们放在Selected附加属性中的这个功能在我的程序中工作(在我的真实程序中它似乎没有绑定?),但不是在这个最小化版本中。我不知道为什么然而,代码似乎做了它需要做的所有事情。

我用来测试它的代码:

.xaml.cs

namespace MyNamespace
{
    public partial class MainWindow
    {
        public IList Selected { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            Selected = new List<object>();
            Why.ItemsSource = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        }
        private void Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(Selected.Cast<object>().Aggregate("", (s, info) => $"{s}{info}, ").TrimEnd(',', ' '));
            MessageBox.Show(Extensions.GetSelected(Why).Cast<object>().Aggregate("", (s, o) => $"{s}{o}, ").TrimEnd(',', ' '));
        }
    }
    public static class Extensions
    {
        public static readonly DependencyProperty SelectedProperty = DependencyProperty.RegisterAttached(
            "Selected", typeof(IList), typeof(Extensions), new PropertyMetadata(default(IList), HookSelectionChanged));

        private static void HookSelectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ListBox lb = sender as ListBox;
            if (lb == null)
                throw new ArgumentException("This property currently only supports DependencyObjects inheriting from Selector.", nameof(sender));
            lb.SelectionChanged += SelectionChanged;
        }

        private static void SelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
            => SetSelected((ListBox)sender, ((ListBox)sender).SelectedItems.Cast<object>().ToList());

        public static void SetSelected(DependencyObject element, IList value) => element.SetValue(SelectedProperty, value);

        public static IList GetSelected(DependencyObject element) => (IList)element.GetValue(SelectedProperty);
    }
}

.xaml

<Window x:Class="MyNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:lcl="clr-namespace:MyNamespace"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="My title." Height="350" Width="425" MaxHeight="350" MaxWidth="425" MinHeight="350" MinWidth="425">
    <StackPanel>
        <ListBox lcl:Extensions.Selected="{Binding Selected}" x:Name="Why" SelectionMode="Extended"/>
        <Button Click="Click" Content="blah"/>
    </StackPanel>
</Window>

任何想法都会很棒!谢谢:))

1 个答案:

答案 0 :(得分:2)

好吧,所有这一切都让我错过了两件事:

  • 我在测试中没有实现INotifyPropertyChanged
  • 我不知道Binding一直没有默认为TwoWay

所有需要做的就是:

.xaml.cs

namespace MyNamespace
{
    public partial class MainWindow : INotifyPropertyChanged
    {
        private IList _selected;

        public IList Selected
        {
            get { return _selected; }
            set
            {
                if (Equals(value, _selected)) return;
                _selected = value;
                OnPropertyChanged();
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            Selected = new List<object>();
            Why.ItemsSource = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        }
        private void Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(Selected.Cast<object>().Aggregate("", (s, info) => $"{s}{info}, ").TrimEnd(',', ' '));
            MessageBox.Show(Extensions.GetSelected(Why).Cast<object>().Aggregate("", (s, o) => $"{s}{o}, ").TrimEnd(',', ' '));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public class Extensions
    {
        public static readonly DependencyProperty SelectedProperty = DependencyProperty.RegisterAttached(
            "Selected", typeof(IList), typeof(Extensions), new FrameworkPropertyMetadata(default(IList), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, HookSelectionChanged));

        private static void HookSelectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ListBox lb = sender as ListBox;
            if (lb == null)
                throw new ArgumentException("This property currently only supports DependencyObjects inheriting from Selector.", nameof(sender));
            lb.SelectionChanged += SelectionChanged;
        }

        private static void SelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
            => SetSelected((ListBox)sender, ((ListBox)sender).SelectedItems.Cast<object>().ToList());

        public static void SetSelected(DependencyObject element, IList value) => element.SetValue(SelectedProperty, value);

        public static IList GetSelected(DependencyObject element) => (IList)element.GetValue(SelectedProperty);
    }
}

它的工作非常出色。