Text = {Binding}上没有显示数据?

时间:2011-05-25 13:25:40

标签: c# silverlight xaml windows-phone-7 binding

我对Silverlight和Windows 7手机的开发还很陌生。而且我不确定我错过了什么,但我很遗憾我错过了一些东西,因为它没有按预期工作。

我的目标是展示一个只有他们的名字和生命值的生物列表。但整个Text = {Binding} -stuff显然不起作用。所以我想知道你们中的任何人是否可以帮助我。

当我说它不起作用时,因为数据在生物列表中,而不在页面/文本块中 - 它显示了正确数量的生物,但不是数据。

XAML

<phone:PhoneApplicationPage 
x:Class="RPG_Assistent.Pages.DamageTrackerPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <!--<Button Content="Damage" Height="72" HorizontalAlignment="Left" Margin="0,618,0,0" Name="btnDamage" VerticalAlignment="Top" Width="160" Click="btnDamage_Click" />
        <TextBox Height="72" HorizontalAlignment="Left" Margin="158,618,0,0" Name="txtDamage" Text="" VerticalAlignment="Top" Width="286" KeyUp="NumericOnlyTextBox_KeyUp"></TextBox>-->
        <ListBox ItemsSource="{Binding creatureList}" Height="500" HorizontalAlignment="Center" Margin="6,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="400">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Width="400" Height="120" >
                        <Button.ContentTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" Height="80" Width="200">
                                    <StackPanel Orientation="Vertical" Height="40">
                                        <TextBlock Width="100" FontSize="22" Text="Name:" Height="40"/>
                                        <TextBlock Width="100" Text="{Binding Name}" Height="40"/>
                                    </StackPanel>
                                    <StackPanel Orientation="Vertical" Height="40">
                                        <TextBlock Width="100" FontSize="22" Text="Hitpoints:" Height="40"/>
                                        <TextBlock Width="100" Text="{Binding HitPoints}" Height="40"/>
                                    </StackPanel>
                                </StackPanel>
                            </DataTemplate>
                        </Button.ContentTemplate>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
            <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->

CS - 当页面加载完成后调用。(在我的DamageTracker页面上的InitializeComponent()之后调用)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace RPG_Assistent.Pages
{
    public partial class DamageTrackerPage : PhoneApplicationPage
    {
        List<Models.Creature> creatureList { get; set; }

        public DamageTrackerPage()
        {
            InitializeComponent();
            creatureList = new List<Models.Creature>();


            #region ApplicationTitle Setup
            ApplicationTitle.Text = Constants.AppName;
            ApplicationTitle.TextAlignment = Constants.AppName_TextAlignment;
            ApplicationTitle.FontSize = Constants.AppName_FontSize;
            ApplicationTitle.FontWeight = Constants.AppName_FontWeight;
            #endregion

           //SetInputScope(txtDamage);


            LoadCreatures();
            DataContext = this;
        }

        public void LoadCreatures()
        {


            string name;

            for (int i = 0; i < 10; i++)
            {
                name = "Monster " + i + 1;
                creatureList.Add(new Models.Creature(name));

            }

        }

        public void btnDamage_Click(object sender, RoutedEventArgs e)
        {

        }

        #region textbox control - makes numeric only
        private void SetInputScope(TextBox textBoxControl)
        {
            InputScopeNameValue digitsInputNameValue = InputScopeNameValue.TelephoneNumber;
            textBoxControl.InputScope = new InputScope()
            {
                Names = {
                    new InputScopeName()
                    {
                        NameValue = digitsInputNameValue
                    }
                }
            };
        }

        private void MaskNumericInput(TextBox textBoxControl)
        {
            string[] invalidCharacters = { "*", "#", ",", "(", ")", "x", "-", "+", " ", "@", "." };

            for (int i = 0; i < invalidCharacters.Length; i++)
            {
                textBoxControl.SelectionStart = textBoxControl.Text.Length;
            }
        }

        private void NumericOnlyTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            MaskNumericInput((TextBox)sender);
        }
        #endregion


    }
}

CS - Creature类,放在“Models”文件夹中 - 因为我认为我会很聪明

using System;

using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RPG_Assistent.Models
{
    public class Creature
    {
        public string Name { get; set; }
        public int HitPoints { get; set; }
        public string Type { get; set; }

        public Creature(string name)
        {
            this.Name = name;
            this.HitPoints = 0;
            this.Type = "Images/mob.jpg";

        }
        public void Damage(int damage)
        {
            HitPoints += damage;
        }
        public void Bloodied()
        {
            switch (this.Type)
            {
                case "Images/mob.jpg":
                    this.Type = "Images/mobhurt.jpg";
                    break;
                case "Images/mobhurt.jpg":
                    this.Type = "Images/mob.jpg";
                    break;
            }
        }

    }
}

5 个答案:

答案 0 :(得分:3)

由于您绑定了一个Creatures列表,因此您不需要输入Creature.Name。您应该能够将其更改为Text = {Binding Name}和Text = {Binding Hitpoints}

答案 1 :(得分:1)

看起来应该是Text = {Binding Name}或Text = {Binding HitPoints}

编辑:但是,Text = {Binding Path = Name}或Text = {Binding Path = HitPoints}也可以。

编辑2:对不起,我没有注意到你的评论。我在计算机上没有VS,所以我不能自己尝试,但尝试将DataTemplate上的DataType设置为Creature。

答案 2 :(得分:1)

将绑定更新为以下内容。我从绑定路径上掉下了生物。然后它应该工作

<StackPanel Orientation="Vertical" Height="40">
  <TextBlock Width="100" FontSize="22" Text="Name:" Height="40"/>
  <TextBlock Width="100" Text="{Binding Path=Name}" Height="40"/>
</StackPanel>
<StackPanel Orientation="Vertical" Height="40">
   <TextBlock Width="100" FontSize="22" Text="Hitpoints:" Height="40"/>
   <TextBlock Width="100" Text="{Binding Path=HitPoints}" Height="40"/>
 </StackPanel>

答案 3 :(得分:1)

您始终使用直接绑定绑定到DataContext,并且在将ItemsSource设置为列表时,DataContext将成为列表中每个要表示的行的项目。所以你的想法完全正确!

然而:ContentControl行为相同。当您设置Content的{​​{1}}时,您基本上覆盖了内容的DataContext。因此ContentControl被设置为您的StackPanel,它将自己呈现为您的StackPanel,但您也将尝试绑定到StackPanel,而不再绑定到您的Creature对象。

所以你可能想要这样做:

将内容StackPanel移动到DataTemplate,将此DataTemplate设置为Button上的ContentTemplate,并将Button的内容设置为Creature对象的Binding,如下所示:

DataContext

答案 4 :(得分:0)

我处理这些场合的首选方法是为视图设置一个集合。它看起来像这样

public class CreatureList : ObservableCollection<Creature>
{
    // at least implement the constructor
}

之后,您可以在窗口XAML定义中使用新的集合类。

<ResourceDictionary>
    <local:CreatureList x:Key="creatures" />
</ResourceDictionary>

必须将本地名称空间的定义设置为将在其中找到类CreatureList的程序集名称空间。之后,您可以使用列表框定义中的已定义列表。

<ListBox Name="creatureListBox" ItemsSource="{Binding Source={StaticResource creatures}}">
    <!-- Template definition for each entry -->
</ListBox>

要在窗口类中使用这些对象,您必须设置一些属性并将它们与指定的条目相关联。

public partial class DamageTrackerPage : PhoneApplicationPage
{
    private readonly CreatureList creatureList;
}

在类的构造函数中,将属性绑定到指定的XAML定义。

public DamageTrackerPage() {
    InitializeComponent();
    creatureList = FindResource("creatures") as CreatureList;
}

现在,当您向列表中添加条目或从中删除条目时,更改将自动更新到您的窗口。

这至少是我在WPF中的方式,但我确信WinPhone应用应该是相同的。