我试图让它工作几天。 这段代码有什么问题?
这是我的窗口 XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Rapideo_Client"
x:Class="Rapideo_Client.MainWindow"
Title="NVM" SnapsToDevicePixels="True" Height="400" Width="625">
<Window.Resources>
<DataTemplate x:Key="linksTemplate" DataType="DownloadLink">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold"></TextBlock>
<Label Content="{Binding Path=SizeInMB}"/>
<Label Content="{Binding Path=Url}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Visible"
x:Name="MainListBox"
ItemTemplate="{DynamicResource linksTemplate}">
</ListView>
</Window>
这是我的课:
class Rapideo
{
(...)
public List<DownloadLink> Links { get; private set; }
(...)
}
这是我的元素:
class DownloadLink
{
public string Name { get; private set; }
public string Url { get; private set; }
public DateTime ExpiryDate { get; private set; }
public float SizeInMB { get; private set; }
public int Path { get; private set; }
public string Value { get; private set; }
public LinkState State { get; set; }
public enum LinkState
{
Ready, Downloading, Prepering, Downloaded
}
public DownloadLink(string name, string url, DateTime expiryDate, float sizeInMB, int path, string value, LinkState state)
{
Name = name;
Url = url;
ExpiryDate = expiryDate;
SizeInMB = sizeInMB;
Path = path;
Value = value;
State = state;
}
}
这是我的绑定(bind):
RapideoAccount = new Rapideo();
MainListBox.ItemsSource = RapideoAccount.Links;
在代码的后面,我在 RapideoAccount.Links 中填充了该列表。 但是 ListView 中没有显示任何内容。 ListView 始终为空。
这段代码哪里出错了?
请您参考如下方法:
是的,它应该是一个 ObservableCollection<DownloadLink>如果您打算在设置 ItemsSource 之后添加它.如果列表已预加载且您不会更改它,List<T>会奏效的。
现在我确实认为
MainListBox.ItemsSource = RapideoAccount.Links;
在技术上仍然是一种绑定(bind)。但是您可能想到的是通过 DataContext 绑定(bind)而不是直接绑定(bind)(都是 MVVM 风格)。那就是:
RapideoAccount = new Rapideo();
this.DataContext = RapideoAccount;
然后在您的窗口中,您将像这样绑定(bind) ItemSource:
<Window
...
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Visible"
x:Name="MainListBox"
ItemsSource="{Binding Links}"
ItemTemplate="{DynamicResource linksTemplate}">
</ListView>
</Window>
