第四章 WPF框架数据绑定过程以及相关属性
一、数据绑定中的相对数据源处理
二、集合通知
在这里插入图片描述
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using WpfApp1.Models;
namespace WpfApp1.Base
{
public class AttachBase
{
//依赖附加属性 关系的是被附加的对象
public static ObservableCollection<DataModel2> GetItemsSource(DependencyObject obj)
{
return (ObservableCollection<DataModel2>)obj.GetValue(ItemsSourceProperty);
}
public static void SetItemsSource(DependencyObject obj, ObservableCollection<DataModel2> value)
{
obj.SetValue(ItemsSourceProperty, value);
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.RegisterAttached("ItemsSource", typeof(ObservableCollection<DataModel2>), typeof(AttachBase), new PropertyMetadata(null,new PropertyChangedCallback(OnPropertyChanged)));
//发生关系的回调方法
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var p = d as WrapPanel;
var list = e.NewValue as ObservableCollection<DataModel2>;
//ItemsSource = new ObservableCollection<>... 触发值 变化回调
//向ItemSource里添加子项,并不会触发值 变化回调,CollectionChanged
list.CollectionChanged += (se, ev) =>
{
p.Children.Clear();
FillChiledrn(p,list);
}
;
FillChiledrn(p,list);
}
static void FillChiledrn(WrapPanel wp ,ObservableCollection<DataModel2> list)
{
wp.Children.Clear();
foreach (var item in list)
{
Binding binding = new Binding("Value");
binding.Source = item;
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10, 5, 10, 5);
BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, binding);
wp.Children.Add(textBlock);
}
}
}
}
三、绑定常见的属性
1.mode