[英]WPF - Binding to collection in object
我试图让它工作几天。 这段代码有什么问题?
这是我的 window 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:
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 中没有显示任何内容。 列表视图始终为空。
该代码中的错误在哪里?
是的,它应该是ObservableCollection<DownloadLink>
如果您计划在设置ItemsSource
之后添加它。 如果列表已预加载并且您不会更改它,则List<T>
会起作用。
现在我确实认为
MainListBox.ItemsSource = RapideoAccount.Links;
在技术上仍然是一个绑定。 但是您可能想到的是通过 DataContext 而不是直接绑定(al la MVVM 风格)。 所以那是:
RapideoAccount = new Rapideo();
this.DataContext = RapideoAccount;
然后在您的 window 中,您将像这样绑定您的 ItemSource:
<Window
...
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Visible"
x:Name="MainListBox"
ItemsSource="{Binding Links}"
ItemTemplate="{DynamicResource linksTemplate}">
</ListView>
</Window>
我认为 Links 需要是一个ObservableCollection
,而不是一个列表。
首先,如果您打算在设置绑定后更改列表,则应该使用ObservableCollection<DownloadLink>
而不是List<DownloadLink>
。
其次,要明确一点:
MainListBox.ItemsSource = RapideoAccount.Links;
不是绑定。 你只是在设置属性。 这适用于某些场景,但它不像我们通常在 WPF 中谈论的那样真正绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.