【发布时间】:2017-05-23 22:14:21
【问题描述】:
我正在尝试将我的 UserControl 的 DataContext 设置为 UserControl 的代码隐藏类。从代码隐藏方面做起来真的很容易:
public partial class OHMDataPage : UserControl
{
public StringList Stuff { get; set; }
public OHMDataPage ()
{
InitializeComponent();
DataContext = this;
}
}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
但是我怎样才能完全从 XAML 端和 UserControl 级别执行此操作?如果我这样做(并从代码隐藏中删除 DataContext = this;),它适用于子节点:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
我真的很想了解如何在 UserControl 本身上执行此操作。我希望这会起作用:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
但事实并非如此。
【问题讨论】:
-
嗯,似乎
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"在我的 MainWindow 上有效,但在此 UserControl 上无效。这很奇怪...... -
ScrollViewer 中的 ListBox 有什么意义?
-
刚刚开始学习。主要使用占位符的东西。我在 ListBox 上看到了 HandlesScrolling 属性。我猜你问是因为 ListBox 已经实现了滚动?
-
没错,将一个滚动组件放入另一个滚动组件时要小心