我有一个带有自定义 DataTemplate 的 ListView:
<ListView Name="lvDataBinding" VerticalAlignment="Top" Margin="0,200,0,30" ScrollViewer.CanContentScroll="False" BorderBrush="Transparent" BorderThickness="0">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<templates:ZoneTemplate Name="dataTemplate" Margin="-5,0,-5,0" Width="160"/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
我想要完成的是动态更改(从 C# )DataTemplate 的宽度。我尝试了 Width
参数的Data Binding
,但它似乎不起作用。
有什么建议吗?
最佳答案
我不知道你是如何填充列表的,以及你使用哪个虚拟机,所以我做了一些解决方案作为示例:
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListView Name="lvDataBinding" VerticalAlignment="Top" Margin="0,200,0,30" ScrollViewer.CanContentScroll="False" BorderBrush="Transparent" BorderThickness="0">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Rectangle Fill="AntiqueWhite" Stroke="Black" StrokeThickness="1"
Height="50"
Name="dataTemplate"
Margin="-5,0,-5,0"
Width="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=Window}, Path=ItemWidth}"/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
<TextBox Grid.Row="1" Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window},
Path=ItemWidth}"/>
</Grid>
并在该窗口的cs文件中:
public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register(
"ItemWidth", typeof (int), typeof (MainWindow), new PropertyMetadata(170));
public int ItemWidth
{
get { return (int) GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
关于c# - 动态更改DataTemplate的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502653/