我有一个ListView,我想绑定到一个项目列表(Items),但我希望TextBlocks中显示的内容。
这是我的xaml:
<Window.DataContext>
<local:WindowViewModel/>
</Window.DataContext>
<Canvas Style="{StaticResource MainCanvasStyle}">
<ListView Name="MainListView" Style="{StaticResource MainListViewStyle}" SelectionChanged="ListView_SelectionChanged">
<TextBlock Text="{Binding Items.Number}"/>
<TextBlock Text="{Binding Items.Type}"/>
</ListView>
</Canvas>
这是我的VM:
class WindowViewModel
{
/// <summary>
/// Hides the main window if it's open.
/// </summary>
public ICommand HideWindowCommand
{
get
{
return new DelegateCommand
{
CommandAction = () => Application.Current.MainWindow.Close(),
CanExecuteFunc = () => Application.Current.MainWindow != null
};
}
}
public WindowViewModel()
{
_itemHandler = new ItemHandler();
_itemHandler.Add(new Item("Test1Name", "Test1Type"));
_itemHandler.Add(new Item("Test2Name", "Test2Type"));
}
private readonly ItemHandler _itemHandler;
public List<Item> Items
{
get { return _itemHandler.Items; }
}
}
public class ItemHandler
{
public ItemHandler()
{
Items = new List<Item>();
}
public List<Item> Items { get; private set; }
public void Add(Item item)
{
Items.Add(item);
}
}
public class Item
{
public Item(string number, string type)
{
Number = number;
Type = type;
}
public string Number { get; set; }
public string Type { get; set; }
}
当我启动程序时出现错误:
使用ItemsSource时,操作无效。使用ItemsControl.ItemsSource访问和修改元素。
在线
TextBlock Text =“{Binding Items.Number}”
但我不太明白为什么。
我最好使用带有TextBlocks的画布而不仅仅是普通的TextBlocks,但这是另一件我不确定该怎么做的事。
答案 0 :(得分:1)
将ItemsSource
设置为列表视图,并将ItemTemplate
设置如下:
<ListView Name="MainListView" Style="{StaticResource MainListViewStyle}" ItemsSource="{Binding Items}" SelectionChanged="ListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"/>
<TextBlock Text="{Binding Type}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 1 :(得分:0)
首先,您需要将Items
属性绑定到ItemsSource
:
<Window.DataContext>
<local:WindowViewModel/>
</Window.DataContext>
<Canvas Style="{StaticResource MainCanvasStyle}">
<ListView Name="MainListView" Style="{StaticResource MainListViewStyle}" ItemsSource="{Binding Items}" SelectionChanged="ListView_SelectionChanged">
<TextBlock Text="{Binding Items.Number}"/>
<TextBlock Text="{Binding Items.Type}"/>
</ListView>
</Canvas>
然后,您需要将ItemTemplate属性设置为有效的DataTemplate:
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Number}"/>
<TextBlock Text="{Binding Type}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
我建议你看看Data Templating Overview。