In Silverlight, I am creating a button for every item in an ObservableCollection. I've added an ICommand to handle this on the object which has the ObservableCollection. In the XAML, how do I get back up to this from one of the collection items?
LayoutRoot.DataContext is set to an instance of the following class:
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;
}
}
And using it with this 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>
You can bind to the name of the root element
<Button Command={Binding Path=DataContext.TestCommand, ElementName=LayoutRoot}" />
精彩评论