I'm currently learning how to develop and buildin开发者_开发百科g an app for windows phone 7.
If a certain value is true, I need to add a TextBlock to the ListBox before a TextBlock (say its name is x:Name="dayTxtBx"
).
I am currently using
dayListBox.Items.Add(dayTxtBx);
to add the text box.
Any help very much appreciated!
Thanks
This is pretty easy to do if you're using a DataTemplate and a ValueConverter and passing the whole object into the ListBox (rather than just a string). Assuming you have some object that looks like:
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));
}
}
}
You can make a converter that looks like:
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();
}
}
And add the converter to your XAML like so:
<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>
Then you could have the ListBox defined in XAML like so:
<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>
Might seem like a lot, but it's really pretty simple once you get started. A great way to learn more about data binding and converters is at Jesse Liberty's blog ( http://jesseliberty.com/?s=Windows+Phone+From+Scratch ).
精彩评论