0

我无法理解如何将我的歌曲数据绑定List<>到 aListBox而无需ItemsSource在后面的代码中设置。它虽然有效,但我真的很想看到列表在 liveview Designer 中工作。

命名空间 App5
{
    类 SongsData
    {
        公共字符串标题 { 获取;放; }
        公共字符串歌词 { 获取;放; }
    }
}

在我的 MainPage.xaml.cs 中:

        公共主页()
        {
            this.InitializeComponent();

            列出歌曲 = new List();
            Songs.Add(new SongsData() { Title = "你的歌", Lyrics = "有点好笑.." });
            Songs.Add(new SongsData() { Title = "Rocket Man", Lyrics = "I'm the Rocket Maaaan.." });

            SongsListBox.ItemsSource = 歌曲;
        }

在 XAML 中,我有一个基本的 ListBox:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

一个友好的人可以帮助我了解要改变什么 - 希望是为什么 - 让歌曲标题显示在ListBoxVisual Studio 的实时视图设计器中?

有了上面我必须调试程序才能看到ListBox.

非常感谢。

4

2 回答 2

3

您基本上需要将DesignData构建时间操作应用于您的数据文件。可以在msdn找到非常全面的演练。

于 2013-01-08T19:57:31.210 回答
1

一个快速简单的解决方案是将您移动ListBox到 ​​new UserControl,将列表初始化放在UserControl的构造函数中,然后将 的实例添加UserControl到您的主窗体中。

例子:

歌曲列表控制.cs:

namespace App5
{
    public parital class SongListControl : userControl
    {
        this.InitializeComponent();

        List Songs = new List();
        Songs.Add(new SongsData() { Title = "Your Song", Lyrics = "It's a little bit funny.." });
        Songs.Add(new SongsData() { Title = "Rocket Man", Lyrics = "I'm the Rocket Maaaan.." });

        SongsListBox.ItemsSource = Songs;
    }
}

SongListControl.xaml :

<UserControl x:Class="App5.SongListControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}" />
            </DataTemplate>
        </ListBox.ItemTemplate>        
    </ListBox>
</UserControl>

然后在您的主窗口中:

<Window x:Class="App5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="clr-namespace:App5"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <app:SongListControl />
    </Grid>
</Window>

构建项目时,构造函数初始化将在 MainWindow 预览中进行。

于 2013-01-08T21:12:21.210 回答