【问题标题】:How do I databind to a DataContext further up the tree in Silverlight?如何在 Silverlight 中将数据绑定到树的更上方的 DataContext?
【发布时间】:2011-05-01 19:52:25
【问题描述】:

在 Silverlight 中,我正在为 ObservableCollection 中的每个项目创建一个按钮。我在具有 ObservableCollection 的对象上添加了一个 ICommand 来处理这个问题。在 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>

【问题讨论】:

    标签: c# silverlight xaml data-binding


    【解决方案1】:

    你可以绑定到根元素的名字

    <Button Command={Binding Path=DataContext.TestCommand, ElementName=LayoutRoot}" />
    

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多