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

4

我对Silverlight和Windows 7手机开发比较陌生,不确定自己错过了什么,因为我的应用没有按照预期运行。

我的目标是显示一份包含名称和生命值的生物清单。但是整个“Text={Binding}”似乎无法正常工作。所以我想知道是否有任何人能帮助我解决这个问题。

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

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;
            }
        }

    }
}

你确切地在哪里调用了loadcreatures函数? - Felice Pollano
我不是很确定,但是似乎在绑定表达式中删除类名就可以解决问题了。所以应该是Text={Binding Path=Name}。 - Osiris76
由于您正在XAML中设置creatureList的绑定,请删除listBox.ItemsSource = creatureList。另外,在调用LoadCreatures后,将DataContext设置为此(仅因为尚未设置属性更改通知)。 - Ashley Grenon
你觉得我现在做的怎么样?(现在屏幕上除了我的应用程序标题什么也没有显示出来) - Hans-Henrik
谢谢,但还是不行 :/ 它什么也没显示 ;S 只有名字: 和生命值: 但是没有任何数据 :( - Hans-Henrik
显示剩余4条评论
5个回答

3

由于您绑定到Creature列表,因此不需要使用Creature.Name。您应该能够将其更改为Text={Binding Name}和Text={Binding Hitpoints}


1

请将您的绑定更新为以下内容。我已经从绑定路径中删除了Creature。然后它应该可以工作了。

<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>

1

你总是通过直接绑定到DataContext来进行绑定,当将ItemsSource设置为列表时,DataContext将成为列表中每个项目的数据上下文,以便它能够代表每一行。所以你在这里的想法完全正确!

然而:ContentControl也是一样的。当你设置ContentControl的内容时,你基本上重写了Content的DataContext。因此,DataContext被设置为你的StackPanel,并且它将呈现自己作为你的StackPanel,但你也会尝试绑定到你的StackPanel,而不是你的Creature对象。

所以你可能想要这样做:

将你的内容StackPanel移到DataTemplate中,在你的Button上将这个DataTemplate设置为ContentTemplate,并将Button的内容设置为Creature对象的Binding,像这样:

<Button Width="400" Height="120" Content="{Binding}">
    <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 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>
        </StackPanel>
    </DataTemplate>
    </Button.ContentTemplate>
</Button>

1

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

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

编辑2:抱歉,我没有注意到你的评论。我电脑上没有VS,所以无法自己尝试,但是尝试将DataTemplate上的DataType设置为Creature。


现在它是Text={Binding Name},但仍然无法工作,我漏掉了什么吗?是因为这个类在另一个文件夹中吗? - Hans-Henrik
DataTemplate没有DataType :( - Hans-Henrik
好的,请试一下以下做法:1)将creatureList设置为代码后面类的属性。2)在调用LoadCreatures之后将DataContext设置为this。3)在listbox的xaml中,设置ItemsSource={Binding creatureList},看看是否有效。很抱歉我希望我能够在这台电脑上尝试一下,但没有Visual Studio。 - Ashley Grenon
无法正常工作..如果有人能指导我或提供如何解决此问题的指南链接,我愿意重新做所有工作,因为我在这里疯了:P但我将重新粘贴我的代码到我的第一个帖子中,以便您可以看到我迄今为止所做的工作。 - Hans-Henrik

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应用程序也应该是一样的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接