【问题标题】:Image creation in model在模型中创建图像
【发布时间】:2013-07-16 11:16:46
【问题描述】:

我无法创建同时显示图片的模型,

我的模型类:

   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;

我得到一个空引用异常,我不确定我做错了什么,是否有另一种方法可以将图像添加到数据绑定源?


我试过这个:

 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>

mainpage.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;

mainpage.xaml:

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

但是现在图像应该显示在哪里,它只显示phoneapp7.Model.City,不知道我做错了什么?

【问题讨论】:

  • 使用前需要先实例化Country(即new_city.Country.Source = bi;)。例如:new_city.Country = new Image(someArgsIfAny)

标签: c# xaml binding windows-phone-8


【解决方案1】:

你的模型不应该有Image类型的属性,因为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}"/>

【讨论】:

    【解决方案2】:

    当然,您会遇到空引用异常,因为您没有初始化图像并尝试访问其属性之一。

    在模型中使用 BitmapImage 代替图像。

    然后在模板中的 xaml 中创建 Image 控件并将其与属性 Country 绑定

    在这里查看答案C# initialize class

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 2010-09-27
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多