Skip to main content
 首页 » 编程设计

c#之在 ListBox 中使用自定义 ListBoxItem 定义进行性能分析

2024年02月05日11lautakyan007

我正在尝试分析我的代码的性能,并更好地理解我用作 ListBox 内的 ItemsPanel 的 Canvas 的 WPF 重绘行为。为此,我定义了一个派生自 ListBoxItem 的自定义类 MyListBoxItem(请参见下面的代码)。

不幸的是,我不知道如何在 ListBox 中使用此类。我尝试将 MyListBoxItem 实例列表绑定(bind)到 XAML 中的 ListBox.Items,就像这样 Items="{Binding Path=ListBoxItemsList}",但是然后我得到错误

'Items' property is read-only and cannot be set from markup.

有什么办法可以实现吗?或者也许还有其他选择可以实现我正在做的事情? (即重绘行为分析)

MyListBoxItem的定义:

public class MyListBoxItem : ListBoxItem 
{ 
    public MyListBoxItem(ObjectViewModel vm) 
    { 
        this.DataContext = vm; 
    } 
 
    Size? arrangeResult; 
 
    protected override Size MeasureOverride(Size constraint) 
    { 
        var vm = (this.DataContext as ObjectViewModel); 
        if (vm != null) 
        { 
            Debug.WriteLine("For ObjectViewModel " + vm.Name + ":"); 
        } 
        arrangeResult = null; 
        System.Console.WriteLine("MeasureOverride called for " + this.Name + "."); 
        return base.MeasureOverride(constraint); 
    } 
 
    protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize) 
    { 
        if (!arrangeResult.HasValue) 
        { 
            System.Console.WriteLine("ArrangeOverride called for " + this.Name + "."); 
            // Do your arrange work here 
            arrangeResult = base.ArrangeOverride(arrangeSize); 
        } 
 
        return arrangeResult.Value; 
    } 
 
    protected override void OnRender(System.Windows.Media.DrawingContext dc) 
    { 
        System.Console.WriteLine("OnRender called for " + this.Name + "."); 
        base.OnRender(dc); 
    } 
} 

请您参考如下方法:

您可以创建派生的 ListBox,它覆盖 GetContainerForItemOverride 和 IsItemItsOwnContainerOverride 方法以返回自定义 ListBoxItem:

public class MyListBoxItem : ListBoxItem 
{ 
} 
 
public class MyListBox : ListBox 
{ 
    protected override DependencyObject GetContainerForItemOverride() 
    { 
        return new MyListBoxItem(); 
    } 
 
    protected override bool IsItemItsOwnContainerOverride(object item) 
    { 
        return item is MyListBoxItem; 
    } 
}