【问题标题】:Adding a TextBlock before another element in a ListBox在 ListBox 中的另一个元素之前添加一个 TextBlock
【发布时间】:2010-12-09 17:35:11
【问题描述】:

我目前正在学习如何为 windows phone 7 开发和构建应用程序。

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

我正在使用

dayListBox.Items.Add(dayTxtBx);

添加文本框。

非常感谢任何帮助!

谢谢

【问题讨论】:

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


【解决方案1】:

如果您使用 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>
  <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>

可能看起来很多,但一旦开始,它真的很简单。在 Jesse Liberty 的博客 (http://jesseliberty.com/?s=Windows+Phone+From+Scratch) 中了解有关数据绑定和转换器的更多信息。

【讨论】:

  • 感谢使用您的可见性想法,我设法使用我当前的数据绑定实现。
猜你喜欢
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多