I want to customize a ListView
's ScrollViewer.HorizontalScrollMode
from codebehind. How can I do this?
It is easy in XAML:
<ListView
x:Name="MyListView"
ScrollViewer.VerticalScrollMode="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
ScrollViewer.HorizontalScrollMode="Disabled"
ScrollViewer.HorizontalScrollBarVisibility="Auto">
<!-- ...-->
</ListView>
But how could I do this in C# or C++/CX codebehind?
Disclaimer: I work for Microsoft.
The ScrollViewer
properties (like VerticalScrollMode
, VerticalScrollBarVisibility
, etc) are attached properties (just like AutomationProperties are).
XAML actually provides two methods of setting these properties:
SetValue
and GetValue
)I find the SetValue
pattern super straightforward:
// 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);
(I have not used the other pattern).
This method works for all AttachedProperties (see this similar StackOverflow question).
This works because attached properties are, at their core, DependencyProperties, which provide the SetValue
and GetValue
APIs. From the documentation of attached properties:
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.