2012-01-23 34 views
0

我得到的項目列表框和我使用DataTemplate中顯示的項目進度在ListBoxItem中

我想打一個下載按鈕,當用戶選擇一個項目,然後單擊按鈕進度欄將被添加到選擇的項目數據模式並顯示下載進度,有可能嗎?

任何指針將幫助

<ListBox Name="List" Grid.Row="2" 
       ScrollViewer.HorizontalScrollBarVisibility="Visible" 
       ScrollViewer.VerticalScrollBarVisibility="Disabled" 
       ItemTemplate="{StaticResource ListTemplate}" 
       ItemsSource="{Binding Path=Items}" 
       SelectedItem="{Binding Path=SelectedItem}" 
       ItemContainerStyle="{StaticResource RoundedItem}" 
       BorderBrush="{x:Null}" BorderThickness="0" 
       Background="{x:Null}"> 
      <ListBox.ItemsPanel> 
       <ItemsPanelTemplate> 
        <WrapPanel Margin="10" /> 
       </ItemsPanelTemplate> 
      </ListBox.ItemsPanel> 
     </ListBox> 

感謝

回答

0

是的,這是可能的。您可以創建幷包含該項目的「正常」表示以及進度欄的<ItemTemplate>。最初,您將進度條的Visibility設置爲Collapsed。當下載開始時,您將Visibility更改爲Visible(您可能還想摺疊該項目的其他部分)。

您可以將Visibility屬性數據綁定到該項目的視圖模型的屬性。您可以使用像IsDownloading這樣的布爾屬性,然後通過將true轉換爲Visiblefalse轉換爲Collapsed的轉換器進行綁定。

要顯示進度條,只需將IsDownloading設置爲true並激發PropertyChanged事件。下載完成後,您將IsDownloading設置爲false,並再次觸發PropertyChanged事件。

這是關於如何做到這一點的粗略草圖。你需要一個視圖模型類的項目在ListView,你可以進行數據綁定到:

class Item : INotifyPropertyChanged { 

    public String Name { ... } 

    public Double Progress { ... } 

    public Boolean IsDownloading { ... } 

    ... 

} 

您還需要一個IValueConverter,可以轉換BooleanVisibility

class VisibilityConverter : IValueConverter { 

    public Boolean Invert { get; set; } 

    Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) { 
    var visible = Convert.ToBoolean(value)^Invert; 
    return visible ? Visibility.Visible : Visibility.Collapsed; 
    } 

    Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) { 
    throw NotImplementedException(); 
    } 

} 

你的觀點,應根據在這樣的事情:

<ListBox 
    <ListBox.Resources> 
    <local:VisibilityConverter x:Key="VisibilityConverter"/> 
    <local:VisibilityConverter x:Key="InverseVisibilityConverter" Invert="True"/> 
    </ListBox.Resources> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <Grid> 
     <TextBlock 
      Text="{Binding Name}" 
      Visibility="{Binding IsDownloading, Converter={StaticResource InverseVisibilityConverter}}"/> 
     <ProgressBar 
      Value="{Binding Progress}" 
      Visibility="{Binding IsDownloading, Converter={StaticResource VisbilityConverter}}"/> 
     </Grid> 
    <DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

不錯,但我怎麼能綁定到進度欄,並從vm更新它? – ibm123

+0

@ ibm123 Martin在他的例子中展示了Item類的屬性Progress,它綁定到進度條。這是你想要的。但是您可能想要在BackgroundWorker中進行實際的下載並使用ReportProgress方法。另外,實現線程安全版本的INotifyPropertyChanged可能很有用,它可以使用調度程序的Dispatcher,Invoke/BeginInvoke和CheckAccess方法來實現。 – dowhilefor

+0

好的,非常感謝! – ibm123