如何在代码隐藏中设置 ListView 的“ScrollViewer.HorizontalScrollMode”?

How do I set ListView's `ScrollViewer.HorizontalScrollMode` in codebehind?

我想从代码隐藏中自定义 ListViewScrollViewer.HorizontalScrollMode。我该怎么做?

在XAML中很容易:

<ListView
    x:Name="MyListView"
    ScrollViewer.VerticalScrollMode="Disabled"
    ScrollViewer.VerticalScrollBarVisibility="Hidden"
    ScrollViewer.HorizontalScrollMode="Disabled"
    ScrollViewer.HorizontalScrollBarVisibility="Auto">
    <!-- ...-->
</ListView>

但是我如何在 C# 或 C++/CX 代码隐藏中执行此操作?

ScrollViewer properties (like VerticalScrollMode, VerticalScrollBarVisibility, etc) are attached properties (just like AutomationProperties 是)。

XAML实际上提供了two methods设置这些属性:

  • 属性系统(SetValueGetValue
  • XAML 访问器模式

我发现 SetValue 模式非常简单:

// C++/CX
this->MyListView->SetValue(ScrollViewer::VerticalScrollModeProperty, ScrollMode::Disabled);
this->MyListView->SetValue(ScrollViewer::VerticalScrollBarVisibilityProperty, ScrollBarVisibility::Hidden);
this->MyListView->SetValue(ScrollViewer::HorizontalScrollModeProperty, ScrollMode::Disabled);
this->MyListView->SetValue(ScrollViewer::HorizontalScrollBarVisibilityProperty, ScrollBarVisibility::Hidden);

(其他的我没用过)

此方法适用于所有 AttachedProperties(请参阅 this similar Whosebug question)。


之所以可行,是因为附加属性的核心是 DependencyProperties,它提供 SetValueGetValue API。来自附加属性的文档:

Attached properties for the Windows Runtime are implemented as dependency properties, so that the values can be stored in the shared dependency-property store by the property system. Therefore attached properties expose a dependency property identifier on the owning class.