0
目前,我正在學習如何開發和構建應用程序的Windows手機7添加一個TextBlock另一個元素之前在ListBox
如果某一個值是真實的,我需要一個TextBlock前添加到列表框一個TextBlock(說它的名字是x:Name="dayTxtBx"
)。
我目前使用
dayListBox.Items.Add(dayTxtBx);
添加文本框。
非常感謝任何幫助!
感謝
目前,我正在學習如何開發和構建應用程序的Windows手機7添加一個TextBlock另一個元素之前在ListBox
如果某一個值是真實的,我需要一個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>
可能看起來很多,但一旦你開始,它確實非常簡單。瞭解更多關於數據綁定和轉換器的好方法是在Jesse Liberty的博客(http://jesseliberty.com/?s=Windows+Phone+From+Scratch)。
這是什麼意思「之前」? _左邊_或_左邊_?此外,我建議更好地使用數據綁定:http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx – 2010-12-09 18:31:44
上面。有沒有辦法使用數據綁定,並在元素的值更改時插入文本框? – Jamie 2010-12-09 18:36:48