如何在ListBox的Items中使用绑定到ViewModel的属性

时间:2010-12-21 15:15:35

标签: wpf mvvm

我有一个显示MyObjects集合的ListBox。该集合位于ViewModel中。我想处理ListItem上的按钮单击,但绑定有一些麻烦。如果属性绑定到MyObject属性,DataTemplate中的绑定可以正常工作。但是如何将它从ViewModel绑定到属性?

第二个问题我如何使用处理点击事件的代码中的项目信息。例如,我想从项目的TextBox中打印出文本。

代码就是这样:

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <Button Content="{Binding .}"
                Command="{Binding ClickCommand}" /> <!--It doesn't work-->
    </DataTemplate>

</Window.Resources>
<ListBox x:Name="ListBox"
         ItemsSource="{Binding Path=Objects}"
         IsSynchronizedWithCurrentItem="True"
         ItemTemplate="{StaticResource ItemTemplate}"/>

C#:

public partial class MainWindow : Window
{
    VM m_vm;

    public MainWindow()
    {
        m_vm = new VM();
        this.DataContext = m_vm;
        InitializeComponent();
    }
}

public class VM
{
    ObservableCollection<string> _objects;

    public ObservableCollection<string> Objects
    {
      get { return _objects; }
      set { _objects = value; }
    }

    public VM()
    {
        _objects = new ObservableCollection<string>();
        Objects.Add("A");
        Objects.Add("B");
        Objects.Add("C");
    }

    //I used relayCommand from the John Smith articles
    RelayCommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            if (_clickCommand == null)
            {
                _clickCommand = new RelayCommand(() => this.AvatarClick());
            }
            return _clickCommand;
        }
    }

    public void AvatarClick()
    {
        //how to get here the text from the particular item where the button was clicked?
    }
}

1 个答案:

答案 0 :(得分:11)

您的ListBoxItem将具有来自ObservableCollection对象的字符串项作为DataContext,并且从那里您没有任何AvatarClick RelayCommand。您可以在Binding中使用RelativeSource来使用父ListBox中的DataContext。

对于第二个问题,您可以像这样使用CommandParameter

<强>的Xaml

<DataTemplate x:Key="ItemTemplate">
    <Button Content="{Binding .}"
            Command="{Binding DataContext.ClickCommand,
                              RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
            CommandParameter="{Binding .}"/>
</DataTemplate>

<强>视图模型

public ICommand ClickCommand
{
    get
    {
        if (_clickCommand == null)
        {
            _clickCommand = new RelayCommand(param => this.AvatarClick(param));
        }
        return _clickCommand;
    }
}

public void AvatarClick(object param)
{
    //...
}