如何将数据绑定到UserControl

时间:2014-02-15 19:24:48

标签: c# wpf datagrid user-controls

我有一个带有Button,TextBlock和DataGrid的UserControl:

<UserControl x:Class="WpfApplication1.DataGridControl"
         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">
<Grid Background="Red">
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding Path=RowHeight}"></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding Path=ColumnWidth}"></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <Button Name="MinimizeButton"
            Grid.Row="0"
            Grid.Column="0"
            Height="{Binding Path=RowHeight}"
            Width="{Binding Path=ColumnWidth}"
            Click="MinimizeButton_Click">
    </Button>

    <TextBlock Name="SuitNameTextBlock"
               Grid.Row="0"
               Grid.Column="1"
               Text="{Binding Path=SuitName}">
    </TextBlock>

    <DataGrid Name="TestNameGrid"
              Grid.Row="1"
              Grid.Column="1"
              RowHeight="{Binding Path=RowHeight}"
              AutoGenerateColumns="False"
              HeadersVisibility="None"
              CanUserAddRows="False"
              CanUserDeleteRows="False"
              CanUserReorderColumns="False"
              CanUserResizeColumns="False"
              CanUserResizeRows="False"
              CanUserSortColumns="False"
              IsReadOnly="True"
              ItemsSource="{Binding Path=TestResultList}">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="TestName"
                                Binding="{Binding Path=Name}"
                                Width="1.5*"/>
            <DataGridTextColumn x:Name="TestValue"
                                Binding="{Binding Path=Value}"
                                Width="2*"/>
        </DataGrid.Columns>
    </DataGrid>

</Grid>

这个C#代码:

namespace WpfApplication1
{
public partial class DataGridControl : UserControl, INotifyPropertyChanged
{
    private double _rowHeight;
    private double _columnWidth;

    public DataGridControl()
    {
        InitializeComponent();

        this._rowHeight = 19.0;
        this._columnWidth = 19.0;
        this.TestNameGrid.Visibility = System.Windows.Visibility.Hidden;
        this.Height = this._rowHeight;

        this.DataContext = this;
    }

    public double RowHeight
    {
        get { return this._rowHeight; }
        set { this._rowHeight = value; }
    }

    public double ColumnWidth
    {
        get { return this._columnWidth; }
        set { this._columnWidth = value; }
    }

    private void MinimizeButton_Click(object sender, RoutedEventArgs e)
    {
        if (this.TestNameGrid.Visibility == System.Windows.Visibility.Visible)
        {
            this.TestNameGrid.Visibility = System.Windows.Visibility.Hidden;
            this.Height = this.MinimizeButton.Height;
        }
        else if (this.TestNameGrid.Visibility == System.Windows.Visibility.Hidden)
        {
            this.TestNameGrid.Visibility = System.Windows.Visibility.Visible;
            if (this.TestNameGrid.Items.Count > 0)
                this.TestNameGrid.Height = this.TestNameGrid.Items.Count * this._rowHeight + 2;
            else
                this.TestNameGrid.Height = 0;
            this.Height = this.MinimizeButton.Height + this.TestNameGrid.Height;
        }
    }

    public static readonly DependencyProperty SuitNameProperty = DependencyProperty.Register("SuitName", typeof(string), typeof(DataGridControl));

    public string SuitName
    {
        get { return (string)GetValue(SuitNameProperty); }
        set
        {
            SetValue(SuitNameProperty, value);
            OnPropertyChanged("SuitName");
        }
    }

    public static readonly DependencyProperty TestResultListProperty = DependencyProperty.Register("TestResultList", typeof(ObservableCollection<PairClass>), typeof(DataGridControl));

    public ObservableCollection<PairClass> TestResultList
    {
        get { return (ObservableCollection<PairClass>)GetValue(TestResultListProperty); }
        set
        {
            SetValue(TestResultListProperty, value);
            OnPropertyChanged("TestResultList");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}
}

我使用此用户控件的窗口的xaml如下所示

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="481" Width="626"
    >
<Grid Background="#00BFFF">

    <DataGrid x:Name="TestTemplateDataGrid"
              AutoGenerateColumns="False"
              CanUserAddRows="False"
              ItemsSource="{Binding CfTest>
        <DataGrid.Columns>
            <DataGridTemplateColumn Width="1*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <local:DataGridControl x:Name="ustctl"
                                               DataContext="{Binding}"
                                               SuitName="{Binding Path=Str}" 
                                               TestResultList="{Binding Path=PcList}">
                        </local:DataGridControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

</Grid>

namespace WpfApplication1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    private ObservableCollection<PairClass> _testList;
    private ObservableCollection<PairClass> _testList1;

    private ObservableCollection<ClassForTest> cfTest;

    public MainWindow()
    {
        InitializeComponent();

        _testList = new ObservableCollection<PairClass>();
        _testList.Add(new PairClass("sasha", "bugaga"));
        _testList.Add(new PairClass("sasha1", "bugaga"));
        _testList.Add(new PairClass("sasha2", "bugaga"));
        _testList.Add(new PairClass("sash3", "bugaga"));
        _testList.Add(new PairClass("sasha4", "bugaga"));

        _testList1 = new ObservableCollection<PairClass>();
        _testList1.Add(new PairClass("qwerty", "bugaga"));
        _testList1.Add(new PairClass("qwerty1", "bugaga"));
        _testList1.Add(new PairClass("qwerty2", "bugaga"));
        _testList1.Add(new PairClass("qwerty3", "bugaga"));
        _testList1.Add(new PairClass("qwerty4", "bugaga"));

        cfTest = new ObservableCollection<ClassForTest>();
        cfTest.Add(new ClassForTest() { Str = "one", PcList = _testList });
        cfTest.Add(new ClassForTest() { Str = "two", PcList = _testList1 });

        TestTemplateDataGrid.ItemsSource = CfTest;

        DataContext = this;
    }

    public ObservableCollection<PairClass> TestList
    {
        get { return _testList; }
        set { _testList = value; }
    }

    public ObservableCollection<ClassForTest> CfTest
    {
        get { return cfTest; }
        set { cfTest = value; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}
}

如何将数据绑定到DataGrid中的UserControl?

1 个答案:

答案 0 :(得分:0)

您希望Usercontrol继承使用它的“thing”的datacontext。 usercontrol构造函数中的代码

this.DataContext = this;

阻止了这种情况的发生。继承的datacontext将允许您绑定依赖项属性。