【问题标题】:wpf databinding to the objectwpf 数据绑定到对象
【发布时间】:2014-11-17 18:00:04
【问题描述】:

例如我有一个班级的人:

class Person {
     string Name { get; set; }
}

在我的 wpf 应用程序的 mainWindow 中,我得到了一个带有此类的 ObservableCollection,我想在表格中显示它。 我让它在表格中显示成员(在这种情况下只有名称),但由于某些原因,我在表格中有一个按钮。在此按钮中,我使用 xaml 文件中的“命令”属性将 ICommand 绑定到它。

这就是我到目前为止所做的工作,但我如何将对象“人”本身作为参数发送给命令?我成功地将 xaml 中的命令参数用于 string / int,但是如何发送我在行中显示的对象?

谢谢!

【问题讨论】:

  • 您应该能够使用 CommandParameter="{Binding }" 将对象本身作为 CommandParameter 传递
  • thnx 去试试吧 ;) 它的工作!你太棒了:D
  • 重要的是你要理解为什么会这样......要理解绑定,那个特定行的 DataContext 是一个人,所以 {Binding} 是 {Binding Path=DataContext} 的缩写

标签: wpf object data-binding


【解决方案1】:
<Button Command="{Binding ElementName=}" CommandParameter={Binding ElementName=ObjectToSendWithCommand" />`

听起来您没有在 CommandParameter 值中正确绑定对象。我需要成为代码隐藏或 ViewModel 中的公共属性(如果您使用的是 MVVM),如果此值发生更改,则需要使用 PropertyChanged 事件。

希望这是有道理的。

【讨论】:

    【解决方案2】:

    你的 Xaml 文件看起来像

    <ListBox ItemsSource="{Binding MultipleCopyList, Mode=TwoWay}">
     <ListBox.ItemTemplate>
    <DataTemplate>
          <StackPanel Orientation="Horizontal">
             <TextBlock Text="{Binding HeaderText,Mode=TwoWay}" Grid.Column="1"  /> 
          </StackPanel>
        </DataTemplate>
    </ListBox>
    

    你的触发器看起来像

    <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonUp">
    
    
    <cmd:EventToCommand Command="{Binding DataContext.MouseClickCommand,  RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter ="{Binding}" />
    </i:EventTrigger>
    </i:Interaction.Triggers>
    

    你的 ViewModel 看起来像

    private RelayCommand<StateForm> _MouseClickCommand;
        public RelayCommand<StateForm> MouseClickCommand
        {
            get {
                if (_MouseClickCommand == null)
                {
                    _MouseClickCommand = new RelayCommand<StateForm>(e => MouseClick(e));
                }
                return _MouseClickCommand; }
            set
            {
                _MouseClickCommand = value;
                RaisePropertyChanged("MouseClickCommand");
            }
        }
      private void MouseClick(StateForm e)
        {
       Your Code goes Here
           }
    

    【讨论】:

      【解决方案3】:

      我尝试做同样的事情,但我没有找到任何方法将Binding 创建到另一个绑定中。我如何解决这个问题:

      我在ICommand 所在的同一位置创建了一个SelectedItem 属性,然后我将集合中的选定项绑定到我的SelectedItem 属性mode=TwoWay。这样,我的SelectedItem 属性中始终有集合的选定项,并且在ICommand 中我可以访问它。

      希望这可以帮助您解决问题...

      【讨论】:

        猜你喜欢
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-09
        相关资源
        最近更新 更多