简体   繁体   中英

Resize GridView Items in UWP

I'm looking for a way to resize the width of my GridView items programmatically. I have a <GridView> that uses a <DataTemplate> and one of the GridView item's children has a width set. I'm looking to change that width on a button click.

My initial attempt was going to use an integer set in the code behind which would be updated with the new width and then figuring out a way to refresh the GridView but I can't access the integer due to <DataTemplate> changing the context/scope for x:Bind . Is there a better way to achieve this?

<GridView x:Name="gridView1" ItemsSource="{x:Bind Orders}">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="data:Order">
            <RelativePanel Width="200"></RelativePanel>
            </RelativePanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

For your requirement, you could bind RelativePanel Width with specified Source . I have created a setting class that use to management items Width. Then init a setting instance in 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

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

Usage

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

If you want to update the items width you could modify the Setting Width property in button click event.

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

Update

Move to Page Resources

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

Usage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM