【问题标题】:Is there a way to bind the command to a ListView or ComboBox selection?有没有办法将命令绑定到列表视图或组合框选择?
【发布时间】:2017-04-15 18:35:56
【问题描述】:

我无法找到将命令绑定到我的listviewcombobox 选择事件或使用mvvm 的任何鼠标单击事件的方法。

<StackPanel Orientation="Horizontal" >
     <ComboBox Name="cmbID" Width="150"  Margin="10" Height="30" SelectedItem="{Binding CmbSelected,Mode=TwoWay}" DisplayMemberPath="ID" ItemsSource="{Binding MyStudent,Mode=TwoWay}"/>
     <Button Name="btnGetDetail"  Margin="10" Command="{Binding getDetails}" Content="Get Details" Height="30" Width="90"/>
     <TextBox Name="tbName1" Width="90" Height="30" Text="{Binding ElementName=cmbID,Path= SelectedItem.Sub}"></TextBox>
</StackPanel>

xaml 中的命令属性与我们得到的按钮不同。

【问题讨论】:

  • ComboBox 上拥有一个Command 属性不太合乎逻辑——您希望它做什么?有许多方法可以对 WPF 事件做出反应,例如行为或触发器。如果您可以添加有关您想要做什么的更多详细信息,我认为您会得到更多答案
  • 您好先生,我正在将可观察集合绑定到我的组合框,并将 SelectedItem 属性绑定到我的类的一个属性。我想要做的是当我从组合框中选择任何值时假设我选择了 ID (我选择 displaymemberpath 作为 ID)代表 ID 我想在我的列表框中绑定其他数据,因为我无法正确绑定它stackoverflow.com/questions/40904574/… 请查看此线程以获取更多详细信息

标签: c# wpf mvvm combobox


【解决方案1】:

如果您使用 MVVM 模式,要在 ListViewComboBox 中选择项目时执行方法,您只需将其放入您的 SelectedItem 设置器中即可。使用您的示例,在您的视图模型中,您必须具有如下属性:

private object _cmbSelected;
public object CmbSelected
{
     get
     {
         return this._cmbSelected;
     }
     set
     {
         this._cmbSelected= value;
         //Here you can put your method  
         NotifyPropertyChanged("CmbSelected");
     }
}

当一个项目被选中时,setter 被调用,在那里你可以调用任何你想要的方法。在本例中,将object 更改为适当的类型。

【讨论】:

【解决方案2】:

您可以使用System.Windows.Interactivity提供的EventTriggers和InvoceCommandActions。

<Window mlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
...
    <ComboBox SelectedItem="{Binding CmbSelected, Mode=TwoWay}" ItemsSource="{Binding MyStudent}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding YourCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    <ComboBox/>
...
</Window>

顺便说一句,将ItemsSource Binding 设置为TwoWay 模式是没有意义的。顾名思义,它是一个来源,永远不会更新绑定的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2012-02-08
    • 2012-08-23
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多