我有以下Windows RT應用程序。我將一個字符串列表綁定到TextBlocks的ItemsControl。這會將空字符串顯示爲「System.Collections.Generic.List'1 [System.String]」,而不僅僅是一個空字符串。我希望它顯示一個空字符串,而不是DataContext的類型。TextBlock綁定顯示類名而不是空字符串
代碼後面:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DataContext = new List<string>() { "", "not empty string" };
}
}
XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontSize="25"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
輸出:
System.Collections.Generic.List'1[System.String]
non empty string
我與傳統WPF相同的例子,它正確顯示空字符串。
編輯 這輸出同樣的東西。背後
代碼:
public class Model
{
private readonly List<string> items = new List<string>() { "", "non empty string" };
public List<string> Items
{
get { return items; }
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DataContext = new Model();
}
}
XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ItemsControl ItemsSource="{Binding Path=Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontSize="25"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
我沒有測試它,但它似乎是在平臺中的錯誤,但無論如何 - 這似乎不是使用綁定的典型主流方式。人們通常將ItemsSource直接設置爲集合或使用公開集合屬性的視圖模型類型,然後將該集合屬性綁定到您的ItemsControl的ItemsSource。我從來沒有見過任何人將DataContext設置爲集合,或者看到一個很好的理由。 – 2013-04-10 17:24:56
這只是一個例子。我正在構建的應用程序將DataContext分配給具有List類型屬性的ViewModel。 –
2013-04-10 18:31:24