【问题标题】:Passing Binding Data to a User Control in a DataGrid将绑定数据传递给 DataGrid 中的用户控件
【发布时间】:2012-06-09 15:01:37
【问题描述】:

我设置了一个绑定到 ObservableCollection 的数据网格。此网格中的一列由需要从父数据网格绑定到的 ObservableCollection 获取数据的用户控件填充。是否可以绑定子用户控件以使用 ObervableCollection 中的数据?我使用的 XAML 是:

<Window x:Class="Hotspots_Control.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Hotspots_Control"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:viewModel/>
</Window.DataContext>
<DataGrid ItemsSource="{Binding areaList}" Name="hotspotsGrid" AutoGenerateColumns="False" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Area" Binding="{Binding Path=area}" IsReadOnly="True"/>
        <DataGridTemplateColumn Header="Alarms">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <local:AlarmView/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

网格绑定到“viewModel”对象内的“areaList”。我需要让 AlarmView 用户控件能够访问 ObservableCollection 中的每个对象。有没有办法做到这一点?

【问题讨论】:

    标签: wpf binding datagrid datacontext


    【解决方案1】:

    使用DataContext 属性设置绑定对象:

    <DataTemplate>
      <local:AlarmView DataContext="{Binding}"/>
    </DataTemplate>
    

    由于 DataTemplate 已经绑定到 areaList,您可以使用直接绑定设置 DataContext。从这里,子视图将可以访问areaList 对象。

    【讨论】:

      【解决方案2】:

      我会将列表传递给实体 vm 的构造函数,然后您可以从那里访问它,因为您可以将它存储在私有成员中。

      也许有另一种可能更适合的解决方案,但我没有足够的关于该问题的详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-08
        • 2012-03-21
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        相关资源
        最近更新 更多