实现逻辑的好方法是在ListBox(MVVM)中选择和项

本文关键字:MVVM 选择 ListBox 方法 实现 | 更新日期: 2023-09-27 18:29:27

因此,我在windows phone应用程序中实现了MVVM(轻型工具包)。我有一个ListBox,SelectedItem绑定到属性SelectedArticle。下面是(非常简单的)属性:

private Article _selectedArticle;
public Article SelectedArticle
{
    get { return _selectedArticle; }
    set
    {
            _selectedArticle = value;
            base.RaisePropertyChanged("SelectedArticle");
    }
}

所以我想要的是更改视图,当ListBox的元素被选中时。不管怎样,把观点的变化放在长椅上会很容易,但我想避免这种情况。那么如何做到这一点呢?

这里的xaml:

    <ListBox IsEnabled="{Binding ListBoxEnabled, Mode=TwoWay}" SelectedItem="{Binding SelectedArticle, Mode=TwoWay}" Opacity="{Binding Opacity, Mode=TwoWay}" ItemsSource="{Binding ArticlesList}" Height="634" Width="456">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image
                        Margin="0,15"
                        VerticalAlignment="Top"
                        Source="{Binding Image}"
                        Height="100"
                        Width="100" />
                    <StackPanel>
                        <TextBlock Margin="10,15" 
                                   Width="250"
                                   TextWrapping="Wrap"
                                   VerticalAlignment="Top"
                                   HorizontalAlignment="Left"
                                   FontSize="24"
                                   Text="{Binding Content}" />
                        <TextBlock Margin="20,0"
                                   Width="100"
                                   VerticalAlignment="Top"
                                   HorizontalAlignment="Left"
                                   FontSize="20"
                                   Text="{Binding Id}"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

实现逻辑的好方法是在ListBox(MVVM)中选择和项

您想要像交互触发器这样的东西吗
将此添加到您的xaml

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Tap">
        <cmd:EventToCommand Command="{Binding EventTapCommand, Mode=OneWay}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

然后在ViewModel 中定义RelayCommand

public RelayCommand EventTapCommand { get; private set; }
public MainViewModel()
{
    EventTapCommand = new RelayCommand(DoSomeCoolStuff);
}

如果需要,也可以从列表中传递所选项目,只需设置CommandParameter并使用项目类型定义RelayCommand即可。我忘记了确切的绑定语法。类似于:

<cmd:EventToCommand Command="{Binding EventTapCommand, Mode=OneWay}" CommandParameter="{Binding}"/>
public RelayCommand<MyType> EventTapCommand { get; private set; }

您可以使用以下行为将命令附加到ListBox的某个事件:

http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx

看看这篇文章http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/,它使用wpf数据模板根据数据绑定属性显示不同的视图。