【问题标题】:How to get the current view inside a FlipView?如何在 FlipView 中获取当前视图?
【发布时间】:2012-09-24 23:42:05
【问题描述】:

我有一个 FlipView,在 DataTemplate 中有一些控件。由于它位于 FlipView 中,因此它将生成这些控件的多个副本。如果我想找到当前 FlipView 视图中的控件(即在屏幕上/可见),我该怎么做?

我可以在里面的控件上查看加载的事件,但是它会被多次调用,我不知道显示的是哪一个。

【问题讨论】:

  • 你想让控件绑定到flipview.SelectedItem吗?
  • 我想是的。似乎如果 FlipView 有 5 个子项,那么这些控件将有 5 x(某个数字)= n 个实例,并且对于那些 n 个控件中的 5 个控件,它们的 DataContext == flipView.SelectedItem 并且我想要获取 RichTextBlock跨度>
  • 为什么需要视图中的控件?如果您需要更新文本,最好通过绑定来完成。
  • 确实更有意义。不幸的是,我们需要使用一个库,该库接受一个 RichTextBlock 并直接从解析 HTML 中放入 Inlines。如果可能的话,我会绑定一个 Paragraph.Inlines,但似乎我无法对该属性进行数据绑定(无论如何都是只读的)。

标签: xaml data-binding windows-runtime datatemplate winrt-xaml


【解决方案1】:

创建一个可以从 ViewModel 绑定到 RichTextBlock 的 Attached Dependency Property,例如:

public static class MyStaticClass
{
    public static readonly DependencyProperty IsVisible = DependencyProperty.RegisterAttached("IsVisible", typeof(bool), typeof(MyStaticClass), new PropertyMetadata(false, OnVisibilityChanged));

    private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var rtb = (RichTextBlock)d;
        var isVisible = (bool)e.NewValue;

        // Do something to rtb.Inlines  
    }
}

使用此属性,您可以将其绑定到 ViewModel 的 IsSelected 属性:

<FlipView ItemsSource="{Binding SomeList}" SelectedItem="{Binding SelectedVM, Mode=TwoWay}">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <RichTextBlock ns:MyStaticClass.IsVisible="{Binding IsSelected}" />
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>

当 SelectedItem 发生变化时,您可以将子 View Model 上的 IsSelected 设置为 true,这会触发 MyStaticClass.OnVisibilityChanged 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多