2010-12-09 55 views
0

目前,我正在学习如何开发和构建应用程序的Windows手机7添加一个TextBlock另一个元素之前在ListBox

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

我目前使用

dayListBox.Items.Add(dayTxtBx); 

添加文本框。

非常感谢任何帮助!

感谢

+0

这是什么意思“之前”? _左边_或_左边_?此外,我建议更好地使用数据绑定:http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx – 2010-12-09 18:31:44

+0

上面。有没有办法使用数据绑定,并在元素的值更改时插入文本框? – Jamie 2010-12-09 18:36:48

回答

3

这是很容易做到,如果你使用一个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> 

可能看起来很多,但一旦你开始,它确实非常简单。了解更多关于数据绑定和转换器的好方法是在Jesse Liberty的博客(http://jesseliberty.com/?s=Windows+Phone+From+Scratch)。

相关问题