ListView被选中

时间:2013-02-05 18:52:27

标签: c# xaml windows-8 winrt-xaml

我的xaml中有一个listview,我填充了这样的项目:

List<DataLayer.Models.Dictionary> dicts = DataLayer.Manager.getDictionaries();

if (dicts != null)
{
    foreach (DataLayer.Models.Dictionary dict in dicts)
    {
         this.itemListView.Items.Add(dict);
    }
}

我的DataLayer.Models.Dictionary对象具有isSelected属性以及NameSubName

名称和子名称在模板中工作正常,但是如何在用户点击项目时获取项目并进行更新?

谢谢!

修改

我的xaml现在看起来像这样,但项目仍未选中

    <ListView
        x:Name="itemListView"
        TabIndex="1"
        Grid.Row="1"
        Margin="0,60,0,0"
        Padding="0,0,0,0"
        IsSwipeEnabled="False"
        ScrollViewer.VerticalScrollBarVisibility="Hidden"
        SelectionChanged="itemListView_SelectionChanged_1"
        SelectionMode="Multiple"
        FontFamily="Global User Interface">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="IsSelected" Value="{Binding Source=Selected,Mode=TwoWay}"/>
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Margin="6">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Grid.Column="0" Margin="0,0,0,0">
                        <TextBlock Text="{Binding Name}"/>
                        <TextBlock Text="{Binding SubName}" Style="{StaticResource CaptionTextStyle}" TextWrapping="Wrap"/>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

1 个答案:

答案 0 :(得分:8)

[编辑] 刚刚注意到这个问题实际上并没有标记为WPF;但我希望它仍然适用。

WPF本身就是MVVM。直接操作代码背后的控件通常不是一个好主意。因此建议创建一个名为ViewModel的“视图友好”模型; See Here。此外,对于任何用途的绑定,在更改的环境中,您必须通知对属性和/或集合的更改,以便可以更新控件。

首先,你有一个字典集合,所以你创建这个集合,以便它可以通知变化; ObservableCollection可以做到这一点。作为一般经验法则,WPF使用的任何集合都应该使用ObservableCollection,和/或从中派生。

所以这里是竞争工作的例子:

请记住,我正在使用FODY注入我的PropertyChanged提升者; See done manually

public class Dict : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Name { get; set; }
    public string SubName { get; set; }
    public bool Selected { get; set; }
}

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<Dict> Dictionaries { get; set; }

    public ViewModel()
    {
        Dictionaries = new ObservableCollection<Dict>()
        {
            new Dict()
                {
                    Name = "English",
                    SubName = "en",
                    Selected = false,
                },

                new Dict()
                {
                    Name = "English-British",
                    SubName = "en-uk",
                    Selected = true
                },

                new Dict()
                {
                    Name = "French",
                    SubName = "fr",
                    Selected = true
                }
        };

        Dictionaries.CollectionChanged += DictionariesCollectionChanged;
    }

    private void DictionariesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch(e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach(var dict in e.NewItems.Cast<Dict>())
                    dict.PropertyChanged += DictionaryChanged;
                break;
            case NotifyCollectionChangedAction.Remove:
                foreach (var dict in e.OldItems.Cast<Dict>())
                    dict.PropertyChanged -= DictionaryChanged;
                break;
        }
    }

    private void DictionaryChanged(object sender, PropertyChangedEventArgs e)
    {
        Dict dictionary = (Dict)sender;

        //handle a change in Dictionary
    }
}

有了这个,你可以随时添加或删除对象,虽然这里我只是在构造函数中初始化它们。

然后你会在你的窗口或控件中有这个。我已经包含了名称空间,使其更加独立;但这将是WPF名称空间。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:WpfApplication1">

    <Window.Resources>
        <local:ViewModel x:Key="viewmodel"/>
    </Window.Resources>

    <ListView
        x:Name="itemListView"
        DataContext="{StaticResource ResourceKey=viewmodel}"
        ItemsSource="{Binding Path=Dictionaries}"
        SelectionMode="Multiple">

        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="IsSelected" Value="{Binding Path=Selected, Mode=TwoWay}"/>
            </Style>
        </ListView.ItemContainerStyle>

        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Margin="6">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Grid.Column="0" Margin="0,0,0,0">
                        <TextBlock Text="{Binding Name}"/>
                        <TextBlock Text="{Binding SubName}" TextWrapping="Wrap"/>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Window>

如果你的集合没有使用ObservableCollection,那么在加载WPF之后开始向它添加元素它永远不会通知绑定管理器应该更新ListView。

上面的启动:

On start, unfocused

通过覆盖所选的返回值,您可以轻松地看到基础Dictionaries集合正在被更改(即不仅仅是ListView):

public bool Selected { get { return true; } set {/* do nothing*/ }}

这意味着即使您尝试在视图中取消选择,也始终会选择所有内容。它总是这样:

Always seleted

样式是一个不同的问题,如果没有焦点,列表看起来会有所不同。 See Here

现在可以在代码隐藏中对选择更改做出反应,但这会将逻辑与视图混合。

更新[编辑]以包括检测任何Dict中的更改的能力(包括选择的更改时)

You could look into this to simplify it

希望这会有所帮助。