簡體   English   中英

UWP c#綁定到ItemsPanel /自定義面板(模板)

[英]UWP c# Binding to ItemsPanel / Custom Panel (Template)

我終於設法用自己的面板創建了一個GridView。 布局很好。 現在,我希望能夠將ViewModel的值綁定到我自己的面板上。 你能幫我做到這一點嗎? 目前,我正在更改頁面后面代碼中的值,我不喜歡...

目前,我正在嘗試執行x:Bind並得到一個錯誤:“對象引用未設置為對象的實例。” 我不知道“常規”綁定是否有幫助。 我確實嘗試過,但沒有成功。

  1. 自定義面板

     public class PRGD010_GridViewPanel : Panel { public int NumberRowsOrColumns { get { return (int)GetValue(NumberRowsOrColumnsProperty); } set { SetValue(NumberRowsOrColumnsProperty, value < 1 ? 0 : value); } } public static readonly DependencyProperty NumberRowsOrColumnsProperty = DependencyProperty.Register("NumberRowsOrColumns", typeof(int), typeof(PRGD010_GridViewPanel), new PropertyMetadata(1d, OnNumberRowsOrColumnsPropertyChanged)); private static void OnNumberRowsOrColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { (source as PRGD010_GridViewPanel).InvalidateMeasure(); } public int Offset { get { return (int)GetValue(StartPositionProperty); } set { SetValue(StartPositionProperty, value >= this.NumberRowsOrColumns ? this.NumberRowsOrColumns - 1 : value); } } public static readonly DependencyProperty StartPositionProperty = DependencyProperty.Register("Offset", typeof(int), typeof(PRGD010_GridViewPanel), new PropertyMetadata(0d, OnStartPositionPropertyChanged)); private static void OnStartPositionPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { (source as PRGD010_GridViewPanel).InvalidateMeasure(); } public PRGD010_GridViewPanel() { } } 
  2. XAML:

     <GridView ItemsSource="{x:Bind main_viewmodel.prgd010, Mode=OneWay}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <usercontrols:PRGD010_GridViewPanel NumberRowsOrColumns="{x:Bind ViewModel.MyColumns}" Offset="{x:Bind ViewModel.MyOffset" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <GridView.ItemTemplate> <DataTemplate x:DataType="classes:PRGD010_Tag"> <TextBlock Text="{x:Bind ref_cat_id, Mode=OneWay}"/> </DataTemplate> </GridView.ItemTemplate> </GridView> 

當使用x:Bind時,綁定的上下文是頁面或用戶控件本身(而不是普通綁定使用的DataContext),因此在后面的代碼中,您將需要main_viewmodel,View Model和ref_cat_id的屬性。 如果其中一個或多個為空或不存在,那將解釋您得到的錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM