c# - XAML DataTemplate 数据绑定(bind)

标签 c# xaml data-binding datatemplate

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

当我在 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;
        }
    }
}

最佳答案

尝试将 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;
    }
}

关于c# - XAML DataTemplate 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567687/

相关文章:

asp.net - 在 DropDownList 上调用 DataBind() 时出现 ArgumentNullException

javascript - Ember.js 中的 Bind-attr "for"属性

c# - Control.Invoke 展开外部异常并传播内部异常

c# - 有什么办法让我知道文件是否已被修改?

c# - 托管 C++ dll 中的 XmlnsDefinition

c# - 解决 DataGrid 列宽调整不一致的问题

c# - 使用 Rx( react 性扩展)观察 ObservableCollection 中的特定项目

c# - XmlSerializer.Serialize BOM 缺失

c# - 如何允许用户在使用 C# 的 WPF 中使用 Devexpress 验证验证事件后更改控制焦点?

java - HTML java 数据绑定(bind)