ListView在绑定之前呈现UserControl

时间:2018-11-06 23:51:02

标签: c# xaml mvvm data-binding uwp

简而言之,我的问题是:

  • 我正在Windows Universal / UWP应用中使用return View("RegisterSuccess");(和ListView)渲染不可变项的集合。
  • 由于集合中的项目是不可变的,因此我想避免更改通知代码,而使用有效的DataTemplate默认值。
  • 但是,{x:Bind Mode=OneTime}是在绑定MyUserControl之前渲染的。调试时,我在UserControlViewModel之前看到属性get

如何确保set在呈现UserControlViewModel之前已设置好?


一个完整的示例如下:

MainPage.xaml

OneTime

MainPage.xaml.cs

<Page x:Class="MyApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyApp" xmlns:sys="using:System">
    <ListView ItemsSource="{x:Bind PageViewModel}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="sys:String">
                <local:MyUserControl UserControlViewModel="{x:Bind}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Page>

MyUserControl.xaml

using Windows.UI.Xaml.Controls;
namespace MyApp {
    public sealed partial class MainPage : Page {
        public string[] PageViewModel { get; set; } = new string[] { "Item1", "Item2" };
        public MainPage() { InitializeComponent(); }
    }
}

MyUserControl.xaml.cs

<UserControl x:Class="MyApp.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TextBlock Text="{x:Bind ViewModel}" />
</UserControl>

此代码呈现一个包含两行的页面,其中包含文本“默认值”;相反,我的目的是显示值“ Item1”和“ Item2”。


如果我们将using Windows.UI.Xaml.Controls; namespace MyApp { public sealed partial class MyUserControl : UserControl { public string UserControlViewModel { get; set; } = "Default Value"; public MyUserControl() { InitializeComponent(); } } } 设为空的PageViewModel,并在以后填充它,则问题仍然存在。有趣的是,将ObservableCollection<string>替换为ListView,或完全删除ListBox,将ListView放在set之前,并按预期进行渲染:

MainPage.xaml

get

1 个答案:

答案 0 :(得分:0)

借助some help from FEC-4RP at an MSDN forum,我开始了解发生了什么。通过为MyUserControl的每个实例分配唯一的ID,并在ListView中呈现它们的100个,我看到控件被框架回收。因此,他们显然还需要支持后期绑定。

也就是说,似乎ListView在设计控件绑定之前会渲染控件,并且OneTime绑定在UI Virtualizing面板中是不允许的。但是,我不确定,因为我还没有在文档中找到这个。

我怀疑VirtualizingStackPanel.VirtualizationMode的默认值已从Recycling in UWP更改为Standard in .NET

添加DependencyProperty并将MyUserControl(或所有依赖于控件视图模型的所有绑定,通常是所有绑定)上的默认绑定模式设置为除OneTime以外的其他东西似乎是必要的

请在此处进行更全面的解释,我会接受您的回答,否则,请在完成后在此处提供完整的信息。

相关问题