代码之家  ›  专栏  ›  技术社区  ›  shannon

ListView在绑定前呈现UserControl

  •  0
  • shannon  · 技术社区  · 7 年前

    简而言之,我的问题是:

    • 我正在使用 ListView (和 DataTemplate )在Windows Universal/UWP应用程序中。
    • 因为集合中的项是不可变的,所以我希望避免更改通知代码并使用高效的 {x:Bind Mode=OneTime} 违约。
    • 然而, MyUserControl 在其 UserControlViewModel 是绑定的。调试时,我看到一个属性 get 之前 set

    用户控制视图模型 在渲染之前设置 OneTime


    完整示例如下:

    <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>
    

    主页.xaml.cs

    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

    <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>
    

    using Windows.UI.Xaml.Controls;
    namespace MyApp {
        public sealed partial class MyUserControl : UserControl {
            public string UserControlViewModel { get; set; } = "Default Value";
            public MyUserControl() { InitializeComponent(); }
        }
    }
    

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


    PageViewModel 空的 ObservableCollection<string> 以后再填充,问题仍然存在。有趣的是 具有 ListBox ,或删除 列表视图 设置 得到

    主页.xaml

    <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">
        <local:MyUserControl UserControlViewModel="{x:Bind PageViewModel[0]}" />
    </Page>
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   shannon    7 年前

    some help from FEC-4RP at an MSDN forum MyUserControl 一个唯一的ID并在一个 ListView ,我看到控件被框架回收。因此,它们显然也需要支持后期绑定。

    也就是说,ListView似乎在通过设计绑定控件之前呈现控件,并且 OneTime UI虚拟化面板中不允许绑定。但是,我不确定,因为我还没有在文档中找到这个。

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

    添加DependencyProperty并设置上的默认绑定模式 我的用户控件 (或依赖于控件的viewmodel的所有绑定,通常是所有绑定)到 一次

    请随意在这里更完整地解释,我会接受你的答案,否则我会在这里完成完整的信息,当我完成。

    推荐文章