【问题标题】:Resize GridView Items in UWP在 UWP 中调整 GridView 项的大小
【发布时间】:2019-01-23 05:01:01
【问题描述】:

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

我最初的尝试是在代码中使用一个整数集,该整数集将使用新的宽度进行更新,然后想办法刷新GridView,但由于<DataTemplate>,我无法访问整数更改x:Bind 的上下文/范围。有没有更好的方法来实现这一点?

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

【问题讨论】:

    标签: c# uwp uwp-xaml


    【解决方案1】:

    根据您的要求,您可以将RelativePanel 宽度与指定的Source 绑定。我创建了一个用于管理项目宽度的设置类。然后在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>
    

    用法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多