0

写真も表示するモデルを作成するのに問題があります。

私のモデルクラス:

   public class City
{
    public string Name
    {
        get;
        set;
    }

    public Image Country
    {
        get;
        set;
    }
}

次に、私のmainpage.xaml.csで:

List<City> source = new List<City>();
 BitmapImage bi = new BitmapImage(new Uri("/PhoneApp7;component/Images/test.png",    UriKind.Relative));
        City new_city = new City();

        new_city.Name = "Africa";
        new_city.Country.Source = bi;
        new_city.Language = "xhosa";

        source.Add(new_city);

        citiesList.ItemsSource = source;

nullreference 例外が発生しました。何が間違っているのかわかりません。また、データバインディングのためにソースに画像を追加する別の方法はありますか?


私はこれを試しました:

 public class City
{
    public City(Uri countryUri)
    {
        Country = new BitmapImage(countryUri);
    }

    public string Name
    {
        get;
        set;
    }

    public BitmapImage Country
    {
        get;
        set;
    }

    public string Language
    {
        get;
        set;
    }
}

app.xaml:

  <DataTemplate x:Key="citiesItemTemplate">
        <StackPanel Grid.Column="1"  VerticalAlignment="Top">
            <TextBlock Text="{Binding Name}" FontSize="26"  Margin="12,-12,12,6"/>
            <Image Source="{Binding Path=Country}" />
            <TextBlock Text="{Binding Language}" Foreground="Orange" />
        </StackPanel>
    </DataTemplate>

メインページ.xaml

  List<City> source = new List<City>();

        Uri bi = new Uri("/Images/test.png", UriKind.Relative);
        City new_city = new City(bi) { Name = "Africa", Language = "xhosa", };

        new_city.Name = "Africa";
        new_city.Language = "Xhosa";

        source.Add(new_city);

        citiesList.ItemsSource = source;

メインページ.xaml:

  <phone:LongListSelector  x:Name="citiesList"  
                                 Background="Transparent"
                                 ItemTemplate="{Binding citiesItemTemplate}"
                                 />

しかし、画像が表示されるはずの場所に phoneapp7.Model.City しか表示されません。何が間違っているのかわかりませんか?

4

2 に答える 2

1

はビューに属するコントロールであるImageため、モデルに type のプロパティを設定しないでください。Image次のように変更します。

public class City
{
    public string Name { get; set; }
    public ImageSource Country { get; set; }
}

次に、次のようにプロパティを割り当てます。

new_city.Country = bi;

モデルで画像の URL を使用することもできます。

public class City
{
    public string Name { get; set; }
    public Uri Country { get; set; }
}

new_city.Country = new Uri(...);

どちらの場合でも、モデルにバインドされたプロパティImageを持つコントロールがビューに含まれます。Source

<Image Source="{Binding Country}"/>
于 2013-07-16T11:30:19.387 に答える
0

もちろん、画像を初期化せずにそのプロパティの 1 つにアクセスしようとしたため、null 参照例外が発生します。

モデルでは、イメージの代わりに BitmapImage を使用します。

次に、テンプレートの xaml で Image コントロールを作成し、Country プロパティにバインドします。

ここで答えを確認してくださいC#初期化クラス

于 2013-07-16T11:27:39.933 に答える