在Silverlight中,我正在为ObservableCollection中的每个项创建一个按钮。我添加了一个ICommand来处理具有ObservableCollection的对象。在XAML中,如何从其中一个集合项中恢复此操作?
LayoutRoot.DataContext设置为以下类的实例:
public class MainViewModel
{
public ICommand TestCommand { get; protected set; }
public ObservableCollection<string> Test { get; protected set; }
public MainViewModel()
{
Test = new ObservableCollection<string>();
Test.Add("Hello");
TestCommand = new DelegateCommand(Test, CanTest);
}
private void Test(object parameter)
{
Test.Add("Test text");
}
private bool CanTest(object parameter)
{
return true;
}
}
并将其与此XAML一起使用:
<StackPanel x:Name="LayoutRoot" Background="White">
<ItemsControl ItemsSource="{Binding Test}" />
<Button Command="{Binding TestCommand}">Push Me</Button> <!-- I can access TestCommand when I bind to it here -->
<ItemsControl ItemsSource="{Binding Test}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}"
Command="{Binding Path=TestCommand, Source=?????}" <!-- But how do I get back to the TestCommand from here? -->
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
答案 0 :(得分:2)
您可以绑定到根元素的名称
<Button Command={Binding Path=DataContext.TestCommand, ElementName=LayoutRoot}" />