XAML 如何将命令绑定到嵌套事件?

6vl6ewon  于 2023-09-28  发布在  其他
关注(0)|答案(2)|浏览(155)

我有richTextBox和想绑定命令到ScrollBar的事件.滚动帮助xmlns:i=http:schemas.microsoft.com/expression/2010/interactivity.我试过,但它不工作:

<RichTextBox >
    <RichTextBox.Document>
        <FlowDocument>
            <Paragraph>
                <ScrollBar>
                    <behaviors:Interaction.Triggers>
                        <behaviors:EventTrigger EventName="Scroll">
                            <behaviors:InvokeCommandAction Command="{Binding UpdateText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=views:MainWindow}}"/>
                        </behaviors:EventTrigger>
                    </behaviors:Interaction.Triggers>
                </ScrollBar>
                <Run Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus}">
                </Run>
            </Paragraph>
        </FlowDocument>
    </RichTextBox.Document>
</RichTextBox>

所以,上面的代码是我的情况,因为我有richtextbox和运行绑定到文本。我尝试绑定ScrollBar的事件。滚动到命令。我可以绑定TextBox的任何事件,但我不知道如何在TextBox中绑定ScrollBar的事件。我的意思是textBox有ScrollBar,它有事件。也许有人知道:有可能吗?
如果你知道常用文本框答案,它也会帮助我。我只想知道有没有可能。谢谢

w6lpcovy

w6lpcovy1#

请参考此实现并使其适合您的需要。

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

<ScrollBar>
  <i:Interaction.Behaviors>
    <behavior:ScrollBehavior ScrollCommand="{Binding MyScrollCommand}" />
  </i:Interaction.Behaviors>
</ScrollBar>
public class ScrollBehavior : Behavior<ScrollBar>
    {
        public ICommand ScrollCommand
        {
            get { return (ICommand)GetValue(ScrollCommandProperty); }
            set { SetValue(ScrollCommandProperty, value); }
        }

        public static readonly DependencyProperty ScrollCommandProperty =
            DependencyProperty.Register("ScrollCommand", typeof(ICommand), typeof(ScrollBehavior), new PropertyMetadata(null,
                OnScrollCommandChanged));

        private static void OnScrollCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = d as ScrollBehavior;

            if(behavior != null)
            {
                behavior.CommandChanged();
            }
        }

        private void CommandChanged()
        {
            this.AssociatedObject.Scroll += AssociatedObject_Scroll;
        }

        private void AssociatedObject_Scroll(object sender, ScrollEventArgs e)
        {
            ScrollCommand.Execute(null);
        }
    }
zlwx9yxi

zlwx9yxi2#

假设UpdateText是命令,并且它是MainWindowViewModel [MainWindowDataContext]的属性,则绑定应为

<behaviors:InvokeCommandAction Command="{Binding Path=DataContext.UpdateText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>

我还建议将UpdateText重命名为UpdateTextCommand,以便更清楚地说明它是什么。

相关问题