繁体   English   中英

如何使用mvvm显示WPF列表框中所选项目的数据?

[英]How to show data from selected item in listbox wpf using mvvm?

我只是在WPF和MVVM表单上进行一些练习到目前为止,我刚刚完成了从列表中加载数据的普通列表框,即当索引更改时,它将其他数据加载到表单上的文本块中

我想改变这个例子。 我希望用户在列表框中选择一个字段,然后单击一个按钮以显示所有其他数据

因此,形式为(usercontrol): 在此处输入图片说明 当有人选择时,例如Cena,他们将看到右侧填写的数据。

我的.xaml代码是:

<UserControl x:Class="SuperstarsRoster.RosterView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:SuperstarsRoster"
         xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="600">

<UserControl.DataContext>
    <local:RosterViewModel/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="250"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <!--SelectedItem="{Binding SelectedPerson}"-->
    <ListBox Grid.Column="0" Margin="0"
              ItemsSource="{Binding RosterList}"
              DisplayMemberPath="Name"
              Name="lstRoster"
              Height="250"
              VerticalAlignment="Top"/>
    <Button Content="Exit" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnExit" Width="150" Command="{Binding ButtonCommand}" CommandParameter="Hai" />
    <Grid x:Name="PersonDetails" Grid.Column="1" DataContext="{Binding SelectedPerson}" Margin="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="150"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Grid.ColumnSpan="2" Text="Person Details" FontSize="15"/>

        <TextBlock Grid.Row="1" Grid.Column="0" Text="Name"/>
        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Name,Mode=TwoWay}"/>

        <TextBlock Grid.Row="2" Grid.Column="0" Text="Brand"/>
        <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Brand,Mode=TwoWay}"/>

        <TextBlock Grid.Row="3" Grid.Column="0" Text="Type"/>
        <TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Type,Mode=TwoWay}"/>

        <Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnChoose" Width="90" Command="{Binding ChooseCommand}" CommandParameter="{Binding ElementName=lstRoster,Path=SelectedPerson}" />
    </Grid>
</Grid>

我的问题是显示按钮:

<Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnChoose" Width="90" Command="{Binding ChooseCommand}" CommandParameter="{Binding ElementName=lstRoster,Path=SelectedPerson}" />

我不知道该怎么办。 我不知道CommandParameters是否应该为空,或其中是否包含某些内容。

我的ViewModel代码是:

#region Show Button

    private ICommand m_ShowCommand;
    public ICommand ShowCommand
    {
        get
        {
            return m_ShowCommand;
        }
        set
        {
            m_ShowCommand = value;
        }
    }

    public void Selected(object obj)
    {
        RaisePropertyChanged("SelectedPerson");
    }

    #endregion

我觉得我的选择是不正确的代码段。 在ViewModel代码上还有:

 #region Roster Details

    public ObservableCollection<Roster> rosterList;
    public Roster selectedPerson;


    public RosterViewModel()
    {

        ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
        ShowCommand = new RelayCommand(new Action<object>(Selected));
        rosterList = new ObservableCollection<Roster>()
        {
            new Roster(){Name="Batista", Brand="Smackdown!", Type="Heel"},
            new Roster(){Name="The Rock", Brand="RAW", Type="Face"},
            new Roster(){Name="John Cena", Brand="RAW", Type="Face"},
            new Roster(){Name="Randy Orton", Brand="Smackdown!", Type="Heel"}
        };

        RaisePropertyChanged("SelectedPerson");
    }

    #endregion

ShowCommand是按钮事件,但我不知道在这里放什么。

理想情况下,用户选择Cena,单击show,然后文本块将填充数组中的数据。

我的RelayCommand类(所有按钮单击的默认值)如下所示:

class RelayCommand : ICommand
{
    private Action<object> _action;

    public RelayCommand(Action<object> action)
    {
        _action = action;
    }

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _action(parameter);
    }

    #endregion

这里还应该有其他东西吗? 还是在ViewModel中?

我使用的是MVVM,因此我的代码在类后面没有代码。

退出按钮有效,这就是为什么我知道命令将起作用的原因。

编辑

我现在更改了一些代码。 首先,显示按钮位于具有数据上下文设置的网格中。 那被拿出来了。 接下来,两个按钮共享相同的命令(ButtonCommand),但是它们具有不同的参数。 退出是“退出”,选择是“海”

在ViewModel代码中,添加并更改了以下内容

 public string Name { get; set; }
    public string Brand { get; set; }
    public string Type { get; set; }

    #region Button Work
    private ICommand m_ButtonCommand;
    public ICommand ButtonCommand
    {
        get
        {
            return m_ButtonCommand;
        }
        set
        {
            m_ButtonCommand = value;
        }
    }

    public void DoAction(object obj)
    {
        if (obj.ToString() == "Hai")
        {
            if (selectedPerson != null)
            {
                this.Name = selectedPerson.Name;
                this.Brand = selectedPerson.Brand;
                this.Type = selectedPerson.Type;
                RaisePropertyChanged(null);
            }                
        }
        if (obj.ToString() == "Exit")
        {
            MessageBox.Show("This program will now close");
            Environment.Exit(0);
        }
    }
    #endregion

这样,可以设置数据,并且可以在需要时填充字段。

首先进行初始化

 public RosterViewModel()
    {
        ButtonCommand = new RelayCommand(new Action<object>(DoAction));

因此,它现在可以工作。

在此处输入图片说明

您实际上有两种选择:

(1)具有绑定到ListBoxSelectedItem的VM属性,然后您不需要使用button命令发送任何参数...您可以仅对当前的SelectedItem执行ChooseCommand (您所知道的) VM)。

要么

(2)将SelectedItem作为参数传递给您的命令,如下所示:

<Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left"
    VerticalAlignment="Bottom" Name="btnChoose" Width="90"
    Command="{Binding ChooseCommand}" 
    CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}" />

请注意,您将需要给列表框起一个名称(x:Name =“ MyListBox”),并且CommandParameter引用该列表框及其SelectedItem属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM