wpf - 将绑定(bind)数据传递到 DataGrid 中的用户控件

标签 wpf binding datagrid datacontext

我已经设置了一个绑定(bind)到 ObservableCollection 的数据网格。该网格中的一列由用户控件填充,该用户控件需要从父数据网格绑定(bind)到的 ObservableCollection 获取数据。是否可以绑定(bind)子用户控件以使用 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>

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

最佳答案

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

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

由于DataTemplate已经绑定(bind)到areaList,因此您可以通过直接绑定(bind)来设置DataContext。从这里, subview 将可以访问 areaList 对象。

关于wpf - 将绑定(bind)数据传递到 DataGrid 中的用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899939/

相关文章:

c# - 使用 MVVM 单击 DataGrid 单个单元格行和列

c# - 这个 Xaml 无效...我不明白为什么

c# - 如何在样式内的 WPF DataTemplate 中使用绑定(bind)

wpf - 在另一个 StaticResource 中引用一个 StaticResource

c# - 在与 WPF 样式上的 setter 属性不同的类型上使用触发器属性

wpf 字典绑定(bind),其中 key=variable

c# - DataGrid过滤,多输入,MVVM,C#

WPF DataGrid,Ctrl+C 后复制到剪贴板,OnCopyingRowClipboardContent

c# - 如何使 WPF ListView 水平,包含的图像被拉伸(stretch)以适应高度?

wpf - 如何将颜色绑定(bind)到文本框背景wpf