C# WPF 列表框选择已更改 MVVM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18959304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:41:51  来源:igfitidea点击:

WPF Listbox selectionchanged MVVM

c#wpfmvvm

提问by mHelpMe

I have a list box in my WPF application. I know how to use the selectionchanged event. However I am trying to follow the MVVM design. However I am not sure how to do this.

我的 WPF 应用程序中有一个列表框。我知道如何使用 selectionchanged 事件。但是我正在尝试遵循 MVVM 设计。但是我不知道如何做到这一点。

I have done this for a button however not sure if I can do the same thing?

我已经为一个按钮做了这个,但是不确定我是否可以做同样的事情?

<Button Grid.Column="0" Name="buttImport" 
    Content="Import File" 
    Command="{Binding CommandButtImport}" 
    Style="{StaticResource ButtonTemplate}"/>

 

 

public class ViewModel : INotifyPropertyChanged 
{       
    // for the button that imports the orders file
    public ICommand CommandButtImport { get; set; }

    public ViewModel() 
    {
        CommandButtImport = new MyCommands(
            ExecuteCommandButtImport,
            CanExecuteCommandButtImport);
    }

    private bool CanExecuteCommandButtImport(object parameter)
    {
        return true;
    }

    // import button
    private void ExecuteCommandButtImport(object parameter)
    {
      // some code
    }
}

EDIT Please ignore code above

编辑请忽略上面的代码

I have changed my code so have reposted below what I currently have. I have a strange issue. The XAML - Main Code contains the code for my datagrid. The block below App - XAML contains the styling for most of my app, but is just a snipet.

我已经更改了我的代码,因此在我目前拥有的内容下方重新发布。我有一个奇怪的问题。XAML - 主代码包含我的数据网格的代码。App - XAML 下面的块包含我的大部分应用程序的样式,但只是一个片段。

Also

Code Line added beneath my datagrid in XAML - Main Code for testing purposes.

在 XAML 中我的数据网格下方添加了代码行 - 用于测试目的的主代码。

<ListBox ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" 
 SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"/>

My datagrid loads fine. When I click on a row, the row expands to show a list of Securities. The issue I have is that in this listbox when I click on an item nothing happens. However the Listbox which I added beneath my datagrid for testing purposes does work. For example I click on one of the items and my row is updated, also the listbox in my row detail becomes selected. Its very strange why the listbox in my rowdetail doesn't work but the one beneath my datagrid does. Any ideas?

我的数据网格加载正常。当我单击一行时,该行会展开以显示证券列表。我遇到的问题是,在这个列表框中,当我点击一个项目时什么也没有发生。但是,我在数据网格下方添加的用于测试目的的列表框确实有效。例如,我单击其中一个项目并更新我的行,我的行详细信息中的列表框也被选中。很奇怪为什么我的 rowdetail 中的列表框不起作用,但我的数据网格下面的列表框起作用。有任何想法吗?

XAML - Main Code

XAML - 主要代码

<StackPanel>
        <!-- The data grid to display orders-->
        <DataGrid DataContext="{Binding OrderBlock}" 
                  x:Name="dataGridOrders" 
                  ItemsSource="{Binding Orders}"
                  Style="{StaticResource DataGridTemplate}"
                  ColumnHeaderStyle="{StaticResource DG_ColumnHeader}"                      
                  RowHeaderStyle="{StaticResource DG_RowHeader}"
                  RowStyle="{StaticResource DG_Row}"
                  CellStyle="{StaticResource DG_Cell}"                      
                  RowDetailsTemplate="{StaticResource DG_RowDetail}"                      
                  AutoGenerateColumns="False"
                  HorizontalAlignment="Stretch" 
                  VerticalAlignment="Stretch"
                  Background="Silver"
                  RowHeaderWidth="30"                      
                  Margin="25,5,20,15">                                                     

            <DataGrid.Columns>                    
                <DataGridComboBoxColumn Header="Action">
                    <DataGridComboBoxColumn.ElementStyle>
                        <Style TargetType="ComboBox">
                            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.StatusList}"/>
                            <Setter Property="IsReadOnly" Value="True"/>
                            <Setter Property="SelectedValue" Value="{Binding StatusGood}"/>
                        </Style>
                    </DataGridComboBoxColumn.ElementStyle>
                    <DataGridComboBoxColumn.EditingElementStyle>
                        <Style TargetType="ComboBox">
                            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.StatusList}"/>
                            <Setter Property="IsReadOnly" Value="True"/>
                            <Setter Property="SelectedValue" Value="{Binding StatusGood}"/>
                        </Style>
                    </DataGridComboBoxColumn.EditingElementStyle>
                </DataGridComboBoxColumn>                    
                <DataGridTextColumn Header="Fund" Binding="{Binding Account}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Security ID" Binding="{Binding Security.ID}" IsReadOnly="True"/>
                <DataGridTextColumn Header="ThinkFolio Security ID" Binding="{Binding ThinkFolioSecurityID}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Security Name" Binding="{Binding Security.Name}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Buy/Sell" Binding="{Binding TransType}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Quantity" Binding="{Binding OrderQunatity, StringFormat=\{0:N0\}}" IsReadOnly="False"/>
                <DataGridTextColumn Header="Currency" Binding="{Binding BuyCurrency}" IsReadOnly="False"/>
                <DataGridTextColumn Header="Manager" Binding="{Binding FundManager}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Order Reason" Binding="{Binding OrderReason}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Reject Reason" Binding="{Binding RejectReason}" IsReadOnly="True" Width="*"/>                    
            </DataGrid.Columns>
        </DataGrid>
        <ListBox ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"/>
        </StackPanel>

App XAML

应用程序 XAML

  <!-- Row Detail Template for Data Grid -->
    <DataTemplate x:Key="DG_RowDetail">
        <Grid x:Name="RowDetailGrid"                  
              Margin="5"
              HorizontalAlignment="Left">
            <Border HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Width="500"
                    Height="80"
                    CornerRadius="5">
                <Border.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Offset="0" Color="Transparent"/>
                        <GradientStop Offset="1" Color="Transparent"/>
                    </LinearGradientBrush>
                </Border.Background>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="2.5*"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/> 
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0"
                               Grid.ColumnSpan="3"
                               Margin="5,0,0,5"
                               HorizontalAlignment="Left"
                               FontSize="12"
                               FontWeight="Bold"
                               Foreground="Black"
                               Text="Select Security Identifier">
                    </TextBlock>
                    <ListBox Grid.Row="1" Grid.ColumnSpan="3" Name="lbIdentifier" ItemsSource="{Binding DuplicateSecurities}" SelectedItem="{Binding Security}"                                 
                             SelectionMode="Single" HorizontalContentAlignment="Stretch">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid Margin="0,2">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Grid.Column="0" Text="{Binding Path=ID}" FontSize="10" HorizontalAlignment="Left" Margin="5,0,0,0"/>
                                    <TextBlock Grid.Column="1" Text="{Binding Path=Name}" FontSize="10" HorizontalAlignment="Left" Margin="5,0,0,0"/>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </Grid>
            </Border>                                        
        </Grid>
    </DataTemplate>

ViewModel

视图模型

public class ViewModel : INotifyPropertyChanged 
{       
    public ICommand CommandButtImport { get; set; }                     // for the button that imports the orders file
    public ICommand CommandButtSend { get; set; }                       // the button where the user sends the orders in our data grid to thinkFolio
    public ICommand CommandButtExit { get; set; }                       // exit application

    private QoEMain _QoEManager;                                        // manages the Model
    public QoEMain QoEManager { get { return this._QoEManager; } set { _QoEManager = value; } }

    private OrderBlocks _orderBlock;                                    // order block - contains all the order information
    public OrderBlocks OrderBlock
    {
        get
        {
            return this._orderBlock;
        }
        set
        {
            this._orderBlock = value;
            OnPropertyChanged("OrderBlock");
        }
    }
 }

OrderBlocks Class which contains the other classes

包含其他类的 OrderBlocks 类

 public class OrderBlocks : INotifyPropertyChanged
{
 private List<Order> _orders;
    [XmlElement("tF_Transactions")]
    public List<Order> Orders { get { return _orders; } set { _orders = value; OnPropertyChanged("Orders"); } }
}

Orders Class

订单类

    public class Order : INotifyPropertyChanged
    {
        Security security;
        public Security Security
        {
            get { return security; }
            set { security = value; OnPropertyChanged("Security"); }
        }

        List<Security> duplicateSecurities;
        public List<Security> DuplicateSecurities
        {
            get { return duplicateSecurities; }
            set { duplicateSecurities = value; OnPropertyChanged("DuplicateSecurities"); }
        }

Security Class

安全等级

 public class Security : INotifyPropertyChanged
 {
    private string _id;
    public string ID
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
            OnPropertyChanged("ID");
        }
    }

    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public Security() { }

    public Security(string newID, string newName)
    {
        ID = newID;
        Name = newName;
    }

Edit - My code now works please see the code snippet below that works for me

编辑 - 我的代码现在可以使用,请查看下面适合我的代码片段

<DataGrid Grid.Row="1" Grid.Column="0" 
     ItemsSource="{Binding SelectedItem.DuplicateSecurities, ElementName=dataGridOrders}" 
     SelectedItem="{Binding SelectedItem.Security, ElementName=dataGridOrders}"> 

采纳答案by Omri Btian

Example of binding ListBox SelectionChangedEvent to command in your ViewModel

将 ListBoxSelectionChanged事件绑定到 ViewModel 中的命令的示例

<ListBox x:Name="myListBox" ItemsSource="{Binding SomeCollection}">
   <ie:Interaction.Triggers>
      <ie:EventTrigger EventName="SelectionChanged">
        <ie:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"  CommandParameter="{Binding ElementName=myListBox, Path=SelectedItem}"/>
    </ie:EventTrigger>
  </ie:Interaction.Triggers>
</ListBox >

In your ViewModel:

在您的ViewModel

public class myViewModel
{

    public myViewModel()
    {
        SelectedItemChangedCommand = new DelegateCommand<object>((selectedItem) => 
        {
             // Logic goes here
        });
    }

    public List<SomeData> SomeCollection { get; set; }

    public DelegateCommand<object> SelectedItemChangedCommand { get; set; }
}

This particular example uses Prism MVVM Framework, but you can apply the same idea with any other MVVM framework you are using as well.

此特定示例使用 Prism MVVM 框架,但您也可以将相同的想法应用于您正在使用的任何其他 MVVM 框架。

Hope this helps

希望这可以帮助

回答by Viv

using SelectionChangedwith MVVM is quite simple:

SelectionChanged与 MVVM 一起使用非常简单:

An approach could be to bind to the SelectedIndexproperty of the ListBoxand in the property setter in the VM, act accordingly as it would be triggered whenever the property changes.

一种方法可能是绑定到VM 中的属性设置器中SelectedIndexListBox和 的属性,相应地进行操作,因为它会在属性更改时被触发。

Example: Here

例子:这里

In this example whenever the selected index changes, the value of that item is increased by one.

在此示例中,只要所选索引发生变化,该项目的值增加了一个。

the main bit is:

主要位是:

public int SelectedIndex {
  get {
    return _selectedIndex;
  }

  set {
    if (_selectedIndex == value) {
      return;
    }

    // At this point _selectedIndex is the old selected item's index

    _selectedIndex = value;

    // At this point _selectedIndex is the new selected item's index

    RaisePropertyChanged(() => SelectedIndex);
  }
}

xaml would just be:

xaml 只是:

<ListBox ItemsSource="{Binding Items}" SelectedIndex="{Binding SelectedIndex}" />

Itemsis the collection of items we bind to.

Items是我们绑定到的项目的集合。