WPF:在UserControl中绑定DataGrid

时间:2015-11-13 18:47:11

标签: c# wpf xaml datagrid user-controls

我有一个usercontrol,里面会有几个datagrids。 想要使绑定工作,但由于某种原因,内容不会显示:

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

在usercontrol中:

  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绑定有效。(添加它以测试绑定是否正常工作)。

谢谢!

1 个答案:

答案 0 :(得分:0)

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>