动态更改DataTemplate的宽度

时间:2017-02-28 07:28:52

标签: c# wpf xaml data-binding

我有一个带有自定义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,但似乎无效。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我不知道你是如何填充你的列表,以及你使用的是哪个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); }
    }