开发者

How to add doubles to a list of doubles from my XAML

I was wondering how I would easily be able to add a list of doubles to a list within my FoodItem class.

My XAML:

<src:FoodItemCollection x:Key="Drinks">
            <src:FoodItem Name="Fountain" ImagePath="Resources\drinks_fountain.png" Price="2.50,2.00,1.50"></src:FoodItem>
            <src:FoodItem Name="Popcan" ImagePath="Resources\drinks_popcan.png" Price="1.50"></src:FoodItem>
            <src:FoodItem Name="Bottle" ImagePath="Resources\drinks_bottle.png" Price="2.00"></src:FoodItem>
            <src:FoodItem Name="Slushy" ImagePath="Resources\drinks_slushy.png" Price="3.50,3.00,2.50"></src:FoodItem>
        </src:FoodItemCollection>

My FoodItem class has a method called Price:

public class FoodItem
{
...
List<开发者_JAVA百科;double> prices = new List<double>();
...

public List<double> Price
        {
            get { return prices; }
            set
            {
                prices = value;
            }
        }
...
}

Unfortunately, the way I am inputting the list of prices in my XAML file is giving me an error. But it is compiling.

The error I am getting is :

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: 'List`1' type does not have a public TypeConverter class. Error at Line 31 Position 85

Line 31 is the code at the top.

Thanks for all the help :)


You can't add items to a list or array (as far as I know) with the XAML syntax you are using in your prices.

Price="3.50,3.00,2.50"

When it is trying to convert (and assign) the multiple prices string into the List at runtime, it throws the exception.

This little example shows you how to add values to an array in Xaml:

<Window x:Class="XamlTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly:mscorlib"
        xmlns:src="clr-namespace:MyTestXaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <src:FoodItem x:Key="Drinks">
                <src:FoodItem.Prices>
                    <sys:Double>3.5</sys:Double>
                    <sys:Double>3.0</sys:Double>
                    <sys:Double>2.5</sys:Double>
                </src:FoodItem.Prices>
            </src:FoodItem>
        </Grid.Resources>
        <ListBox DataContext="{StaticResource Drinks}"
                 ItemsSource={Binding Prices}/>
    </Grid>
</Window>

If you want to put FoodItem into a FoodItemCollection, follow the same pattern, which you are already doing. You just needed to take it a step farther with your prices.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜