7
我有一個ListBox顯示MyObjects的集合。該集合位於ViewModel中。我想處理一個ListItem上的按鈕的點擊,但有一些綁定的麻煩。如果該屬性綁定到MyObject屬性,則DataTemplate中的綁定工作正常。但是,我怎樣才能將它綁定到ViewModel的屬性?如何在列表框的項目中使用綁定到ViewModel的屬性
第二個問題我如何使用處理點擊事件的代碼中的項目信息。例如,我想打印出項目文本框中的文本。
的代碼是這樣的:
<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?
}
}