gpt4 book ai didi

c# - uwp 如何一次调整模板项目源中项目的大小?

转载 作者:行者123 更新时间:2023-11-30 22:55:27 29 4
gpt4 key购买 nike

我有这个 ListView ,我想在窗口大小发生变化时动态调整项目的属性(字体大小、宽度和高度等)。到目前为止,我已经能够通过在 c# 中一个一个地修改项目源的元素布局(使用 for 循环)来做到这一点。随着 ListView 项目数量的增加,效果稍后会出现故障。不知道有没有办法统一修改listview中这些模板化项的样式。我试过使用和修改应用于模板的 staticResource 样式,但无济于事。

 <ListView
x:Name="leftMenubar"
Grid.Column="0"
Height="auto"
VerticalAlignment="Top"
VerticalContentAlignment="Stretch"
IsItemClickEnabled="True"
ItemClick="LeftBarMenuItemClicked"
ItemsSource="{x:Bind Items}"
Loaded="LeftMenubar_Loaded">
<ListView.Resources>
<SolidColorBrush x:Key="ListViewItemBackgroundPointerOver" Color="Transparent" />
<SolidColorBrush x:Key="ListViewItemBackgroundPressed" Color="Transparent" />
<SolidColorBrush x:Key="ListViewItemBackgroundSelectedPressed" Color="Transparent" />
<SolidColorBrush x:Key="ListViewItemBackgroundSelected" Color="Transparent" />
<SolidColorBrush x:Key="ListViewItemBackgroundSelectedPointerOver" Color="Transparent" />
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>

<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel
Margin="0"
VerticalAlignment="Top"
GroupPadding="0"
Orientation="Vertical" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:LeftMenuBarItem">
<StackPanel Margin="0,0,0,0" Padding="{x:Bind Pad, Mode=OneWay}">
<BitmapIcon
Height="{x:Bind IconHeight, Mode=OneWay}"
MinHeight="20"
Margin="0,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Stretch"
Foreground="{x:Bind Foreground, Mode=OneWay}"
UriSource="{x:Bind ImgPath}" />
<TextBlock
Width="Auto"
Margin="0,5,0,0"
HorizontalAlignment="Center"
FontSize="10"
Foreground="{x:Bind Foreground, Mode=OneWay}"
Text="{x:Bind Title}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

最佳答案

您可以通过几种不同的方式完成此操作。您可以设置数据模板以将字体大小绑定(bind)到控件的高度并在那里计算。但是随后您会为列表中的每个项目触发一个转换器。

我认为最好的方法是为 ListViewItem 设置一个绑定(bind)到 ListView 上的 FontSize (和其他属性)这是如何设置的示例

class AdjustableListView : ListView
{
public AdjustableListView()
{
SizeChanged += OnSizeChanged;
}

protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);

var listItem = (ListViewItem)element;
var binding = new Binding { Source = this, Path = new PropertyPath("FontSize")};
listItem.SetBinding(ListViewItem.FontSizeProperty, binding);
}

private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
FontSize = Math.Max(12, e.NewSize.Height / 24);
}
}

关于c# - uwp 如何一次调整模板项目源中项目的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55243804/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com