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

ProfileNameおよびImageSourceフィールドからプロパティに変更してみてください。

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 に答える