WPF : Bind DataGrid Inside UserControl

本文关键字:Inside UserControl DataGrid Bind WPF | 更新日期: 2023-09-27 18:22:00

我有一个用户控件,里面有几个数据网格。想让绑定工作,但由于某些原因,内容没有显示:

 UserControls.iMRxMRDataGrid ucObj = new UserControls.iMRxMRDataGrid();
 ChartDescriptiveClass.PartName="test";
 ucObj.DataContext = ChartDescriptiveClass;

内部用户控制:

  public partial class iMRxMRDataGrid : UserControl
    {
        public iMRxMRDataGrid()
        {
            InitializeComponent();
            DataContext = this;
        }
    }

xaml:

<UserControl x:Name="iMRxMRDataUC" x:Class="SPCLibrary.UserControls.iMRxMRDataGrid"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"             
             >
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>          
        </Grid.RowDefinitions>
        <DataGrid x:Name="iMRxMRDataGri" DataContext="{Binding DataContext,ElementName=iMRxMRDataUC}" AutoGenerateColumns="False">
            <DataGrid.Columns>               
                <DataGridTextColumn Binding="{Binding PartName}" Width="Auto" Header="PartName" IsReadOnly="True" />   <!--This will not work-->             
            </DataGrid.Columns>
        </DataGrid>      
        <TextBlock Grid.Row="1"  Text="{Binding Path=DataContext.PartName,ElementName=iMRxMRDataUC}" Width="40px" Height="30px"/>  <!--This works-->      
    </Grid>
</UserControl>

类如下(每个属性一个成员):

public class ChartDescriptiveValues
    {
        //iMR & xMR
        public string PartName { get; set; }
        public int Count { get; set; }
        public double Average{ get; set; }
        public double LSL { get; set; }
        public double USL { get; set; }
   }

但是textBlock绑定有效。(添加此项是为了测试绑定是否有效)。

谢谢!

WPF : Bind DataGrid Inside UserControl

DataGridTextColumn的绑定将您的列绑定到DataGrid.ItemsSource中的属性,因此您必须设置ItemsSource或重新考虑您想要的内容。

<DataGrid x:Name="iMRxMRDataGri" ItemsSource={Binding SomeCollection} DataContext="{Binding DataContext,ElementName=iMRxMRDataUC}" AutoGenerateColumns="False">
        <DataGrid.Columns>               
            <DataGridTextColumn Binding="{Binding PropertyInDataModelOfSomeCollection}" Width="Auto" Header="PartName" IsReadOnly="True" />          
        </DataGrid.Columns>
    </DataGrid>