我想建立一個控件,根據傳入的類型選擇性地顯示不同的東西,但由於某種原因,我最終沒有顯示任何內容。WPF ContentControl不顯示任何東西
我在這裏失蹤了一些基本的東西嗎? (這段代碼從我的真實生產應用程序中被大規模剝離出來,展現出相同的行爲)
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new List<ContactInformation>
{
new Address {Street = "21 Jump", City = "Sparta", State = "Denial"},
new Phone {Number = "734-555-1212"}
};
}
}
public class ContactInformation
{
}
public class Address : ContactInformation
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class Phone : ContactInformation
{
public string Number { get; set; }
}
<Window x:Class="ContentControlExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:contentControlExample="clr-namespace:ContentControlExample"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ItemsControl ItemsSource="{Binding /}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl DataContext="{Binding /}" Content="{Binding /}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type contentControlExample:Address}">
<StackPanel>
<TextBlock Text="{Binding Street}"/>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}, {1}">
<Binding Path="City"/>
<Binding Path="State"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type contentControlExample:Phone}">
<TextBlock Text="{Binding Number}"/>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
我不知道''{Binding /}「是什麼意思,但我沒有使用它。只需將其更改爲「{綁定}」。 – 2013-04-26 18:54:52
我從來沒有見過綁定使用'/'就像你有......也許這是相關的?一種快速的測試方法是將DataTemplates移動到''並將Your ItemsControl保存爲'。默認情況下,ItemsControl已經用ContentPresenter繪製了你的項目,並且應該使用隱式模板來繪製每個項目。如果這不起作用,請使用[Snoop](http://snoopwpf.codeplex.com/)這樣的工具查看您的可視化樹,並且它是'DataContext',這可能會指向正確的方向。 –
Rachel
2013-04-26 18:55:18
/表示集合的當前項目,因此將表示ContactInformation列表的當前項目。你不需要其他的。 –
Phil
2013-04-26 18:57:03