2

我正在尝试为 WP8 制作应用程序,但我一生都无法弄清楚数据绑定是如何工作的。我已经尝试了一个又一个示例,看起来他们所做的与我几乎完全相同,但似乎没有任何效果。基本上,配置文件类包含配置文件的名称和图标。我想在屏幕上显示这些配置文件的列表,名称在图标的右侧。

当我在 WP8 手机模拟器中运行该项目时,什么也没有出现。如果我将 DataTemplate 中元素的属性(即源和文本)更改为绝对字符串,它可以正常工作。

MainPage.xaml:

<phone:PhoneApplicationPage ..>

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.Resources>
        <DataTemplate x:Name="ProfileListTemplate">
            <StackPanel Margin="10">
                <Image Grid.Column="0" Width="50" Height="50" Source="{Binding ImageSource}" Stretch="Fill"/>
            <TextBlock Grid.Column="1" Text="{Binding ProfileName}" Margin="10" HorizontalAlignment="Left" FontSize="36"/>
            </StackPanel>
        </DataTemplate>
    </Grid.Resources>
    <phone:LongListSelector x:Name="ProfilesList" Grid.Row="1" VerticalAlignment="Top" FontSize="36" Height="535" Margin="10,0,0,0" ItemTemplate="{StaticResource ProfileListTemplate}"/>
</Grid>

</phone:PhoneApplicationPage>

MainPage.xaml.cs:

namespace Profiles
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            ObservableCollection<Profile> ProfilesCollection = new ObservableCollection<Profile>();
            ProfilesCollection.Add(new Profile("Nighttime"));
            ProfilesCollection.Add(new Profile("Work"));
            ProfilesCollection.Add(new Profile("Home"));
            ProfilesList.ItemsSource = ProfilesCollection;
        }
    }
}

“个人资料”类:

namespace Profiles
{
    class Profile
    {
        public string ProfileName = "";
        public string ImageSource = "/Resources/Delete.png";

        public Profile(string name)
        {
            ProfileName = name;
        }
    }
}
4

2 回答 2

2

尝试从字段更改ProfileNameImageSource属性。

class Profile
{
    private const string DefaultImageSource = "/Resources/Delete.png";

    public string ProfileName { get; set; }
    public string ImageSource {get; set; }

    public Profile(string name)
    {
        ProfileName = name;
        ImageSource = DefaultImageSource;
    }
}
于 2012-11-26T15:48:23.540 回答
0

将您的 Profile 类更改为属性,如下所示...

public class Profile
{
    string profileName = "";
    string imageSource = "/Resources/Delete.png";

    public string ProfileName
    {
        get
        {
            return profileName;
        }
        set
        {
            profileName = value;
        }
    }
    public string ImageSource
    {
        get
        {
            return imageSource;
        }
        set
        {
            imageSource = value;
        }
    }

    public Profile(string name)
    {
        ProfileName = name;
    }
}

随着您的逻辑越来越多,添加更多行为并实现 INotifyPropertyChanged 如果您需要跟踪单个对象内的更改,则相对简单。

于 2012-11-26T15:49:46.933 回答