1

如何将另一个用户控件中的元素绑定到命令目标?

这是主要的xml

<Grid>
    <StackPanel>
        <Button Height="200" x:Name="PageUpButton" FontFamily="Marlett" FontSize="40" Content="5" Command="{x:Static ScrollBar.PageUpCommand}" CommandTarget="{Binding ElementName=scrollViewerActive}"/>
        <local:posMenuChild x:Name="PosMenuChild"/>
        <Button Height="200" x:Name="PageDownButton" FontFamily="Marlett"  FontSize="40" Content="6" Command="{x:Static ScrollBar.PageDownCommand}" CommandTarget="{Binding ElementName=ScrollViewerActive }"/>
    </StackPanel>        
</Grid>

我应该指定什么作为 CommandTarget?如何使用顶部窗口中的按钮滚动以下 UserControl 中的元素?

这是用户控件

<Grid Height="200">
    <WrapPanel Orientation="Vertical"  Height="200">
        <ScrollViewer VerticalScrollBarVisibility="Hidden" Name="ScrollViewerActive" CanContentScroll="True" >
            <StackPanel>
                <TextBlock Text="Test1" FontSize="35"/>
                <TextBlock Text="Test2" FontSize="35"/>
                <TextBlock Text="Test3" FontSize="35"/>
                <TextBlock Text="Test4" FontSize="35"/>
                <TextBlock Text="Test5" FontSize="35"/>
                <TextBlock Text="Test6" FontSize="35"/>
            </StackPanel>
        </ScrollViewer>
    </WrapPanel>
</Grid>
4

1 回答 1

0

使用以下内容修改用户控件的代码隐藏:

首先,添加一个DependencyProperty要绑定到的ScrollViewer类型

public static readonly DependencyProperty ScrollTargetProperty = DependencyProperty.RegisterAttached(
        "ScrollTarget", typeof(ScrollViewer), typeof(UserControl1), new PropertyMetadata(null));

public static void SetScrollTarget(DependencyObject element, ScrollViewer value)
{
   element.SetValue(ScrollTargetProperty, value);
}

public static ScrollViewer GetScrollTarget(DependencyObject element)
{
   return (ScrollViewer)element.GetValue(ScrollTargetProperty);
}

不要忘记更改UserControl1为您的用户控件的类名。

然后,将此属性设置为ScrollViewerActive(我在控件的构造函数中完成了它)

SetScrollTarget(this, ScrollViewerActive);

现在你可以像这样绑定它

<Button Command="{x:Static ScrollBar.PageUpCommand}" CommandTarget="{Binding Path=ScrollTarget, ElementName=PosMenuChild, Mode=OneWay}"/>
于 2017-01-17T10:07:04.670 回答