我試圖用我自己的用戶控件集合填充WrapPanel
。Databinding to WrapPanel無法正常工作
子控件:
<UserControl x:Class="MyApplication.StockMappings.StockView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Width="140" Height="80">
<Border CornerRadius="6" BorderBrush="Black" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.6*"/>
<RowDefinition Height="0.4*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" FontSize="18" FontWeight="Bold">
<Label Content="{Binding Path=ID}"/>
</TextBlock>
<TextBlock Grid.Row="1" FontSize="12" FontWeight="Bold">
<Label Content="{Binding Path=StockName}"/>
</TextBlock>
</Grid>
</Border>
</Grid>
</UserControl>
CS文件:
<Window x:Class="MyApplication.StockMappings.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApplication.StockMappings"
Title="TestWindow" Height="300" Width="300">
<Grid>
<ItemsControl Name="Stocks" ItemsSource="{Binding AllStocks}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:StockView/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
和C#代碼再次:
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
var stocks = new[]
{
new StockView() { ID = "M0", StockName = "abc"},
new StockView() { ID = "M1", StockName = "def"},
};
Stocks.DataContext = new Test()
{
AllStocks = stocks.ToList()
};
}
}
namespace MyApplication.StockMappings
{
/// <summary>
/// Interaction logic for StockView.xaml
/// </summary>
public partial class StockView : UserControl
{
public StockView()
{
InitializeComponent();
}
public string ID
{
get;
set;
}
public string StockName
{
get;
set;
}
}
}
最後,與保鮮面板窗口
的Test
類(子數據的容器)是非常簡單的:
public class Test
{
public List<StockView> AllStocks
{
get;
set;
}
}
最後,結果是:
所有邊界是空白。不會顯示ID
和StockName
。
我在做什麼錯?
我已確認(加上空屬性)StockView
控制採取從Test
對象ID
值,而不是從列表AllStocks
孩子。但爲什麼?我有沒有定義ItemTemplate
?那麼,那是什麼?
'我做錯了什麼?' - 一切。用戶界面不適合存儲數據。創建一個合適的Model或ViewModel來存儲這些數據並將你的控件綁定到那個數據上。也讓UI創建UI,不要自己實例化UI元素。 – 2013-04-29 14:48:43