依赖项属性中的ListView.View为null

本文关键字:View null ListView 属性 依赖 | 更新日期: 2023-09-27 18:29:36

我想在我们创建的从ListView派生的控件中禁用列重新排序。此控件称为SortableListView。我认为依赖属性是实现这一点的最佳方式,但((SortableListVIew)source).View返回null。这是代码:

public class SortableListView : ListView
{
    // ...lots of other properties here
    public static readonly DependencyProperty AllowsColumnReorderProperty =
        DependencyProperty.Register(
          "AllowsColumnReorder", 
          typeof(bool), 
          typeof(SortableListView), 
          new UIPropertyMetadata(true, AllowsColumnReorderPropertyChanged));
    public bool AllowsColumnReorder
    {
        get
        {
            return (bool)this.GetValue(AllowsColumnReorderProperty);
        }
        set
        {
            this.SetValue(AllowsColumnReorderProperty, value);
        }
    }
    private static void AllowsColumnReorderPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        ViewBase vb = ((SortableListView)source).View;
        if (vb != null)
        {
            ((GridView)vb).AllowsColumnReorder = (bool)e.NewValue;  
        }
    }

和XAML:

    <TableControls:SortableListView x:Name="QueueViewTable" Margin="0,0,0,0"
                                      Style="{StaticResource ListViewStyle}"
                                      ItemsSource="{Binding Path=QueueList}"
                                      ItemContainerStyle="{StaticResource alternatingListViewItemStyle}"
                                      AlternationCount="2"
                                      SelectionMode="Single"
                                      SortEnabled="False"
                                      AllowsColumnReorder="false">

问题是vb总是为null,因此该方法无法设置AllowsColumnReoder。我非常确信强制转换是有效的,因为代码最初在OnInitialized:中看起来是这样的

    ((GridView)this.View).AllowsColumnReorder = false;

但我需要在视图的特定实例上设置AllowsColumnReorder,所以这段代码不好。

有人能告诉我我做错了什么吗?或者有更好的方法来设置这个属性吗?

依赖项属性中的ListView.View为null

ListViewView属性本身就是一个可能更改的依赖属性。当您设置属性时,它似乎还没有设置

您可能必须重写可排序列表视图中的View属性,以便添加属性更改侦听器,然后在设置视图本身时应用排序属性?

在wpf中,您可以覆盖父类中声明的依赖属性,如下所示:http://msdn.microsoft.com/en-us/library/ms754209.aspx

您可以覆盖View属性的元数据,在您在那里设置的PropertyMetadata参数中,您可以传递一个与上面AllowsColumnReorderPropertyChanged 类似的函数

在该处理程序中,您需要检查新视图是否为gridview,然后设置您的属性。

这样,AllowsColumnReorderView的设置顺序将正确设置您的属性。