单击ListView内的TextBlock将不允许我选择整个ListViewItem

时间:2016-07-12 16:40:54

标签: wpf xaml listview

我得到了以下XAML代码:

<ListView x:Name="myList" Height="447" Background="#FFC8F0F1" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ListViewItem>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding date}" Foreground="{Binding textcolor}" />
                    <TextBlock Margin="5,0,0,0" Text="{Binding foo}" Foreground="{Binding textcolor}" />
                    <TextBlock Margin="5,0,0,0" Text="{Binding bar}" Foreground="{Binding textcolor}" />
                </StackPanel>
            </ListViewItem>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我正在启动我的程序,代码用ListViewItems填充ListView,到目前为止一直很好......

一旦我点击文本(Textblocks a.k.a. StackPanel中的所有内容),它就不会选择/标记ListViewItem(背景区域)。

如果我点击没有文字的免费地点,它可以正常工作。

我甚至尝试将ListView更改为ListBox,它既不能正常工作。

2 个答案:

答案 0 :(得分:0)

您的DataTemplate不应包含ListViewItem个实例,控件会为您创建这些容器。如果需要在容器上设置属性,请使用ListView.ItemContainerStyle

答案 1 :(得分:0)

您可能希望将ListView's ItemsSource绑定到FooBar个对象的ObservableCollection,然后这将是微不足道的:

<强> FooBarsView

<UserControl x:Class="ListViewSelectingItem.View.FooBarsView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:ListViewSelectingItem.View"
         xmlns:vm="clr-namespace:ListViewSelectingItem.ViewModel"
         d:DesignHeight="300"
         d:DesignWidth="300"
         mc:Ignorable="d">
<UserControl.Resources>
    <vm:FooBarsViewModel x:Key="fooBarsList"/>
</UserControl.Resources>
<Grid DataContext="{StaticResource fooBarsList}">
    <ListView ItemsSource="{Binding FooBars}">
        <ListView.ItemTemplate>
            <DataTemplate DataType="{x:Type vm:FooBar}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Foo}"/>
                    <TextBlock Text="{Binding Bar}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>
</UserControl>

<强> FooBarsViewModel

namespace ListViewSelectingItem.ViewModel
{
using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
using Model;
public class FooBarsViewModel : ViewModelBase
{
    public FooBarsViewModel()
    {
        FooBars = new ObservableCollection<FooBar>();
        FooBars.Add(new FooBar { Foo = "Foo 1", Bar = "Bar 1" });
        FooBars.Add(new FooBar { Foo = "Foo 2", Bar = "Bar 2" });
        FooBars.Add(new FooBar { Foo = "Foo 3", Bar = "Bar 3" });
    }

    public ObservableCollection<FooBar> FooBars { get; private set; }
}
}