I have a ListBox which displays the collection of MyObjects. The collection is in the ViewModel. I want to handle a click on the button on the ListItem but have some troubles with binding. The binding in the DataTemplate works fine if the property is bound to the MyObject property. But how can I bind it to the property from the ViewModel?
The second question how I can use the information from the item in the code which handles click event. For instance, I want to print out the text from the item’s TextBox.
The code is like that:
<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?
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…