问题
I finally managed to create a GridView with my own Panel. The Layout is fine. Now I want to be able to Bind Values of my ViewModel to my own Panel. Can you help me doing this. For the moment I'm changing the values in the code behind of the page, which I don't like...
For the moment I'm trying to do the x:Bind and I get an error: "Object reference not set to an instance of an object." I don't know if "normal" Binding will help. I did try it but with no success.
Custom Panel
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() { } }
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>
回答1:
When you use x:Bind, the context of the binding is the page or user control itself (rather than the DataContext that the normal binding uses), so in code behind you would need properties for main_viewmodel, View Model, and ref_cat_id. If one or more of those are null or don't exist, that would explain the error that you're getting
来源:https://stackoverflow.com/questions/34731358/uwp-c-sharp-binding-to-itemspanel-custom-panel-template