2017-02-28 222 views
1

我有這樣的ListView使用自定義的DataTemplate:變化寬度動態

<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 BindingWidth參數,但它似乎不工作。 有什麼建議嗎?

+0

你是怎麼試着綁定'Width'的?什麼'Snoop'或視覺工作室的'輸出'顯示綁定,是否有任何錯誤? – Shakra

+0

' '然後我嘗試從.cs文件設置它,但不會工作。沒有錯誤。 – BlackM

+0

您的ListViewItem的viewmodels是否具有TemplateWidth屬性? – Shakra

回答

0

我不知道你是怎麼填充你列表,以及虛擬機使用,所以我做了一些工作,作爲一個例子周圍:

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