我有一个带有自定义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的宽度。我为Data Binding参数尝试了Width,但似乎没有用。
有什么建议么?

最佳答案

我不知道您是如何填充列表的,以及使用的是哪个VM,因此我以以下示例为例进行了处理:

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

10-06 10:20