私は以下のWindows RTアプリケーションを持っています。私は、List of Stringsを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をコレクションに設定したり、その理由を見たことがありません。 –
これは単なるサンプルです。私が構築しているアプリケーションは、リストのタイプのプロパティを持つViewModelにDataContextを割り当てます。 –