我有一个显示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?
}
}
答案 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)
{
//...
}