[英]WPF Strange problem with dynamically binding items to a new ListBox
這是代碼。 它所做的只是在 StackPanel 中創建一個新的 ListBox 控件並向其中添加一個新項。 該問題在頁面底部進行了描述。
MyWindow.xaml
<Window.Resources>
<DataTemplate x:Key="itemsTemplate">
<Border Width="200" Height="50" >
<ListBox ItemsSource="{Binding Title}" />
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ItemsControl Grid.Column="1"
Grid.Row="0"
ItemsSource="{Binding ElementName=mainWindow, Path=DataItems}"
ItemTemplate="{StaticResource itemsTemplate}">
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
MyWindow.xaml.cs
private ObservableCollection<MyDataItem> dataItems;
public ObservableCollection<MyDataItem> DataItems
{
get { return dataItems; }
}
public Window1()
{
dataItems = new ObservableCollection<MyDataItem>();
InitializeComponent();
}
我的數據項.cs
public class MyDataItem : DependencyObject
{
public string Title
{
get
{
return (string)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
}
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string),
typeof(MyDataItem), new UIPropertyMetadata(""));
public MyDataItem(string title)
{
Title = title;
}
}
添加一個帶有項目的新列表框
void addNewItem_Click(object sender, RoutedEventArgs e)
{
MyDataItem item = new MyDataItem("12");
dataItems.Add(item);
e.Handled = true;
}
在該操作之后,我看到了新的 ListBox 控件,但它的所有項目的字符都被視為單獨的項目,正如你可以看到的@圖片。 為什么?
[ EDIT ]
解決了,我不得不在 class 中到處從字符串更改為列表:
public class MyDataItem : DependencyObject
{
public List<string> Title
{
get
{
return (List<string>)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
}
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string),
typeof(MyDataItem),
new UIPropertyMetadata(new List<string>()));
public MyDataItem(List<string> title)
{
Title = title;
}
}
這是正確的,因為您聲明為每個項目實例化一個列表框。 由於一個項目正在公開一個字符串(因此是一個字符數組),因此列表框為每一行正確顯示一個字符。
為什么要在另一個 ItemsControl 中插入一個 ItemsControl(列表框)?
干杯
因為您將數據源作為字符串提供..它正在將該字符串轉換為集合(字符數組),因為 itemssource 屬性將始終是集合..
如果您仍想在具有單個項目的數據模板中創建一個列表框(在您的情況下是標題)..然后試試這個..
將您的標題屬性更改為列表,並在創建標題時創建一個包含一個字符串的列表。 因此項目源將是列表,並且由於 itemssource 包含一個字符串,因此它將僅創建一項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.