目前,我正在学习如何开发和建设为Windows Phone 7的应用程序。

如果某个值是真实的,我需要一个TextBlock之前添加一个TextBlock到列表框(说它的名字是x:Name="dayTxtBx")。

我目前使用

dayListBox.Items.Add(dayTxtBx);

以添加文本框。

任何帮助,非常感谢!

由于

有帮助吗?

解决方案

这是很容易做到,如果你使用一个DataTemplate和ValueConverter并通过整个对象到ListBox中(而不是只是一个字符串)。假设你有一些对象,看起来像:

public class SomeObject: INotifyPropertyChanged
{
    private bool mTestValue;
    public bool TestValue 
    {
        get {return mTestValue;}
        set {mTestValue = value; NotifyPropertyChanged("TestValue");}
    }
    private string mSomeText;
    public string SomeText
    {
        get {return mSomeText;}
        set {mSomeText = value; NotifyPropertyChanged("SomeText");}
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string name)
    {
        if ((name != null) && (PropertyChanged != null))
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

您可以做一个转换器,看起来像:

public class BooleanVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && (bool)value)
            return Visibility.Visible;
        else
            return Visibility.Collapsed;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

和转换器添加到您的XAML,像这样:

<UserControl x:Class="MyProject.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyProject">
    <UserControl.Resources>
        <local:BooleanVisibilityConverter x:Key="BoolVisibilityConverter" />
    <UserControl.Resources>

然后,你可以在XAML定义像这样的列表框:

<Listbox>
  <Listbox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orentation="Horizontal" >
        <TextBlock Text="Only Show If Value is True" Visibility={Binding TestValue, Converter={StaticResource BoolVisibilityConverter}} />
        <TextBlock Text="{Binding SomeText}" />
      </StackPanel>
    </DataTemplate>
  </Listbox.ItemTemplate>
</Listbox>

可能看起来很多,但它真的很简单,一旦你开始。一个伟大的方式,以了解更多有关数据绑定和转换器是杰西自由的博客( HTTP:/ /jesseliberty.com/?s=Windows+Phone+From+Scratch )。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top