【问题标题】:Binding ItemsSource of Datagrid in a ContentPersenter在 ContentPersenter 中绑定 Datagrid 的 ItemsSource
【发布时间】:2014-12-12 05:18:43
【问题描述】:

我正在创建一个包含 ContentPresenter 的用户控件。我用 Datagrid 填充窗口中的 contentPresenter,将 itemsSource 绑定到列表,但它不起作用。

我的数据网格是空的。但是当我将 Datagrid 移出我的 UserControl 时,我得到了里面的数据。

我的用户控件 XAML:

<UserControl Name="Instance" ...>
    <Grid>
        <ScrollViewer>
            <ContentPresenter Content="{Binding Path=AdditionnalContent, ElementName=Instance}" />
        </ScrollViewer>
    </Grid>
</UserControl>

C#:

public Object AdditionnalContent
{
    get { return (object)GetValue(ContentProperty); }
    set { SetValue(ContentProperty, value); }
}

public static readonly DependencyProperty AdditionnalContentProperty = DependencyProperty.Register("AdditionnalContent", typeof(object), typeof(MyUserControl),
      new PropertyMetadata(null));

我的窗口

<Window Name="win" ...>
    <Grid>
        <my:MyUserControl>
            <my:MyUserControl.AdditionnalContent>
                <!-- Datagrid is empty -->
                <DataGrid ItemsSource="{Binding LIST, ElementName=win}" AutoGenerateColumns="True" />
            </my:MyUserControl.AdditionnalContent>
        </my:MyUserControl>

        <!-- Datagrid have content -->
        <DataGrid ItemsSource="{Binding LIST, ElementName=win}" AutoGenerateColumns="True" />
    </Grid>
</Window>

C#:

public partial class MainWindow : Window
{
    public List<Object> LIST
    {
        get;
        private set;
    }

    public MainWindow()
    {
        fillList();
        InitializeComponent();
    }
}

谢谢

【问题讨论】:

  • 下载 snoopwpf.codeplex.com。您可以使用此工具在应用程序运行时检查您的 UI 并发现绑定错误。
  • 我在电脑上工作,我不是管理员,我无法安装程序...

标签: c# wpf user-controls


【解决方案1】:

您的绑定指向不知道它是什么的Window 元素的属性。它只知道的路径是Window的属性

假设您的 LIST 在 Window 的 DataContext 内。然后,您必须将其明确指向WindowDataContext

<DataGrid ItemsSource="{Binding Path=DataContext.LIST, ElementName=win}" AutoGenerateColumns="True" />

【讨论】:

  • 我尝试了您的代码,但它不起作用。我编辑我的问题以显示窗口的 C# 代码,希望它能提供更多帮助。
【解决方案2】:

我用这段代码解决了我的问题

<Window Name="win" ...>
    <Grid>
        <my:MyUserControl>
            <my:MyUserControl.AdditionnalContent>
                <DataGrid ItemsSource="{Binding LIST, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
            </my:MyUserControl.AdditionnalContent>
        </my:MyUserControl>
    </Grid>
</Window>

我现在不会解决答案,因为我想解释一下共振。 我知道它会尝试为窗口控件找到父级的父级,但是它已经在窗口中声明,所以为什么绑定看不到他的名字的windoe控件。

谢谢

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 2011-07-21
    • 2011-12-17
    • 1970-01-01
    • 2011-07-10
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多