如何解决WPF-绑定到对象中的集合
| 我试图使其工作几天。 该代码有什么问题? 这是我的窗口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;
}
}
这是我的约束:
RapideoAccount = new Rapideo();
MainListBox.ItemsSource = RapideoAccount.Links;
在稍后的代码中,我在RapideoAccount.Links中填充该列表。
但是ListView中什么都没有显示。
列表视图始终为空。
该代码中的错误在哪里?
解决方法
是的,如果您打算在安装
ItemsSource
之后添加到它,它应该是ObservableCollection<DownloadLink>
。如果列表是预加载的,并且您不会更改它,则List<T>
会起作用。
现在我确实认为
MainListBox.ItemsSource = RapideoAccount.Links;
从技术上讲仍然具有约束力。但是您可能会想到的是通过DataContext而不是直接绑定(例如MVVM样式)。因此,将是:
RapideoAccount = new Rapideo();
this.DataContext = RapideoAccount;
然后,在窗口中,您将像这样绑定ItemSource:
<Window
...
<ListView ScrollViewer.HorizontalScrollBarVisibility=\"Disabled\"
ScrollViewer.VerticalScrollBarVisibility=\"Visible\"
x:Name=\"MainListBox\"
ItemsSource=\"{Binding Links}\"
ItemTemplate=\"{DynamicResource linksTemplate}\">
</ListView>
</Window>
祝好运。
麦可
,首先,如果您打算在设置绑定后更改列表,则应使用ѭ4而不是ѭ11。
第二,只是要清楚一点:
MainListBox.ItemsSource = RapideoAccount.Links;
不具有约束力。您只是在设置属性。这将在某些情况下有效,但它并不像我们在WPF中通常所说的那样具有约束力。
,我认为Links必须是ObservableCollection
,而不是List。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。