在UWP中调整GridView项目的大小

时间:2019-01-23 05:01:01

标签: c# uwp uwp-xaml

我正在寻找一种以编程方式调整GridView项目宽度的方法。我有一个使用<GridView>的{​​{1}},并且<DataTemplate>项的子项之一已设置宽度。我希望在单击按钮时更改该宽度。

我最初的尝试是在代码中使用一个整数集,该整数集将使用新的宽度进行更新,然后找出一种刷新GridView的方法,但是由于{ {1}}更改GridView的上下文/范围。有没有更好的方法可以做到这一点?

<DataTemplate>

1 个答案:

答案 0 :(得分:2)

根据您的要求,可以将RelativePanel的宽度与指定的Source绑定。我创建了一个用于管理项目Width的设置类。然后在Application.Resources中初始化一个设置实例。

public class Setting : INotifyPropertyChanged
{
    private double _itemWidth = 200;
    public double ItemWidth
    {
        get { return _itemWidth; }
        set { _itemWidth = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

应用程序资源

<Application.Resources>
    <ResourceDictionary>
        <local:Setting x:Key="Setting"/>
    </ResourceDictionary>
</Application.Resources>

用法

<GridView  x:Name="gridView1" ItemsSource="{x:Bind Orders}" ItemClick="GridView1_ItemClick" IsItemClickEnabled="True">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <RelativePanel Width="{Binding ItemWidth,Source={StaticResource Setting}}" Background="SeaGreen" >
                <TextBlock Text="{x:Bind }"/>
            </RelativePanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

如果要更新项目宽度,可以在按钮单击事件中修改“设置宽度”属性。

private void GridView1_ItemClick(object sender, ItemClickEventArgs e)
{
    ((Setting)Application.Current.Resources["Setting"]).ItemWidth = 500;
}

更新

移至页面资源

<Page.Resources>
    <local:Setting x:Key="Setting"/>
</Page.Resources>

用法

private void GridView1_ItemClick(object sender, ItemClickEventArgs e)
{
    ((Setting)this.Resources["Setting"]).ItemWidth = 500;
}
相关问题