Skip to content

WPF 自定义控件依赖属性、事件

约 186 字小于 1 分钟

WPF

2024-02-28

依赖属性

/// <summary>
/// 细胞数据源
/// </summary>
public ObservableCollection<DetectionProjectTreeDto> CellItemsSource
{
    get => (ObservableCollection<DetectionProjectTreeDto>)GetValue(CellItemsSourceProperty);
    set => SetValue(CellItemsSourceProperty, value);
}
public static readonly DependencyProperty CellItemsSourceProperty = DependencyProperty.Register(
    nameof(CellItemsSource),
    typeof(ObservableCollection<DetectionProjectTreeDto>),
    typeof(CellList),
    new PropertyMetadata(new ObservableCollection<DetectionProjectTreeDto>(), (s, e) =>
    {
        if (s is CellList c)
        {
            var source = (ObservableCollection<DetectionProjectTreeDto>)e.NewValue;
            c.CellItemMenus = new ObservableCollection<CellItemMenu>(source.Select(s => new Models.CellItemMenu { DetectionName = s.DetectionName, Source = s.Source, Count = s.Count }));
            c.CellItemMenus[0].IsSelected = true;

            c.CellTreeView.ItemsSource = source;
        }
    }));

依赖命令、事件

public static readonly DependencyProperty ItemClickCommandProperty
     = DependencyProperty.Register(nameof(ItemClickCommand), typeof(ICommand), typeof(CellList), new PropertyMetadata(null));

 /// <summary>
 /// 页面更新命令
 /// </summary>
 public ICommand ItemClickCommand
 {
     get => (ICommand)GetValue(ItemClickCommandProperty);
     set => SetValue(ItemClickCommandProperty, value);
 }

//调用
 ItemClickCommand.Execute(treeview.SelectedItem);

使用

/***********使用*************/
//xaml
<control:CellList CellItemsSource="{Binding CellTreeDataList}" ItemClickCommand="{Binding ItemClickCommand}" />

//viewmodel
private DelegateCommand<object> _itemClickCommand;
public DelegateCommand<object> ItemClickCommand =>
_itemClickCommand ?? (_itemClickCommand =
new DelegateCommand<object>((d) =>
 {
     DetectionProjectTreeDto dpt = (DetectionProjectTreeDto)d;
 }));