2016-12-28 123 views
0

我有以下页面设置,其中包含具有两列的网格视图:图像和标题。并不是所有的行都有图像,我试图将图像放在行宽的一半。因此,对于没有图像可用的行,文本应填充整行,而具有图像的行可在行的一半处显示图像 ,该行的其余部分为标题。UWP GridView在更改大小时调整一列的大小

我已经使用MathConverter将imageWidth调整为行的实际宽度的一半,但在调整大小时(在桌面上调整主窗口大小时,在更改设备方向时在电话/平板电脑上)图像大小未更新。

<Page.Resources> 
    <local:MathConverter x:Key="MathConverter"/> 
    <ItemsPanelTemplate x:Key="Compact"> 
     <ItemsStackPanel/> 
    </ItemsPanelTemplate> 
    <DataTemplate x:Key="LargeWidthDataTemplate"> 
     <Border BorderThickness="0,0,0,1" HorizontalAlignment="Stretch"> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="Auto"/> 
        <ColumnDefinition Width="*"/> 
       </Grid.ColumnDefinitions> 
       <Image Grid.Column="0" Source="{Binding ImageURL}" MaxWidth="{Binding ActualWidth, ElementName=gridView, Converter={StaticResource MathConverter}}" Margin="4"/> 
       <TextBlock Grid.Column="1" Text="{Binding Title}" 
           Loaded="TextBlock_Loaded" HorizontalAlignment="Stretch" TextAlignment="Left" TextWrapping="WrapWholeWords"/> 
      </Grid> 
     </Border> 
    </DataTemplate> 
</Page.Resources> 

<Grid> 
    <GridView x:Name="gridView" Grid.Row="2" SizeChanged="gridView_SizeChanged" 
       ItemsPanel="{StaticResource Compact}" ItemTemplate="{StaticResource LargeWidthDataTemplate}"> 
     <GridView.ItemContainerStyle> 
      <Style TargetType="GridViewItem"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
       <Setter Property="VerticalContentAlignment" Value="Center"/> 
      </Style> 
     </GridView.ItemContainerStyle> 
    </GridView> 
</Grid> 

回答

0

有关的ElementName绑定的目的,当它改变ActualWidth的不发布更新(由于它的异步和运行时间计算的本质)。不要尝试使用ActualWidth作为ElementName绑定的绑定源。如果您有一个需要基于ActualWidth更新的场景,请使用SizeChanged处理程序。

欲了解更多信息,请参阅FrameworkElement.ActualWidth的备注。

所以你应该可以在你的页面添加一个属性,页面需要实现INotifyPropertyChanged接口。在SizeChanged事件中,我们应该能够将ActualWidth设置为属性。然后我们可以将MaxWidth属性绑定到属性。

例如:

private double myActualWidth; 

public double MyActualWidth 
{ 
    get 
    { 
     return myActualWidth; 
    } 
    set 
    { 
     if (myActualWidth != value) 
     { 
      myActualWidth = value; 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs("MyActualWidth")); 
      } 
     } 
    } 
} 

private void NotifyPropertyChanged(string propertyName) 
{ 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

public event PropertyChangedEventHandler PropertyChanged; 

private void gridView_SizeChanged(object sender, SizeChangedEventArgs e) 
{ 
    this.MyActualWidth = gridView.ActualWidth; 
} 
相关问题