我怎样写这个的ItemsControl所以WPF将使用绑定生成输出网格列 [英] How do I write this ItemsControl so WPF will use bindings to generate columns for the output grid

查看:150
本文介绍了我怎样写这个的ItemsControl所以WPF将使用绑定生成输出网格列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的code是可以使用的两行,以显示在一个表中的对象主要是工作的控制。第一行是头行,第二行显示数据。正在显示的对象的特性可以被定义为在相关的控制。每个项目显示为在生成的表中的列。我不想使用反射来实现这种控制。这个问题是不是反映。

控制有两个问题:

1)。它不是写在WPF表(由于没有一个更好的描述),因为我在code创建对象,而不是让绑定引擎做的工作。我之所以有它codeD的方式做是因为我不知道如何正确code吧。注意:我使用的是网格(应该是什么)的ItemsPanel的控制。我想用一个网格,因为我想要的输出要与边框表格形式。在相关文件控制每个项目我需要与两个的TextBlocks在网格的第一和第二行。我还需要添加列,以便在项目属性的每一项新列显示出来。

2)在BuildDataCell方法创建的绑定不起作用。如果1)解决了这个问题将最有可能得到解决。在控制不能在WPF的形​​式被写入万一我想用它作为-是,如果我可以使绑定工作。

下面的文章显示在我碰到,同时研究这几个StackOverflow的问题。它要么不回答我的问题或解答,但我不知道为什么。
http://drwpf.com/blog/2009/05/12/itemscontrol-l-is-for-lookless/#TemplatingAnItemsControl
这篇文章也是相关的,但我不能把它应用到这个问题:
http://blog.scottlogic.com/2010/11/15/using-a-grid-as-the-panel-for-an-itemscontrol.html

InfoTable.cs

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls的;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.ComponentModel;
使用System.Runtime.CompilerServices;命名空间InfoTableHost
{
公共类InfoTableItem:DependencyObject的
{
    公共字符串头
    {
        {返回(字符串)的GetValue(HeaderProperty); }
        集合{的SetValue(HeaderProperty,值); }
    }    公共静态只读的DependencyProperty HeaderProperty =
        DependencyProperty.Register(头,typeof运算(字符串)的typeof(InfoTableItem),新PropertyMetadata(的String.Empty));    公共字符串数据
    {
        {返回(串)的GetValue(DataProperty); }
        集合{的SetValue(DataProperty,值); }
    }    公共静态只读的DependencyProperty DataProperty =
        DependencyProperty.Register(数据的typeof(串)的typeof(InfoTableItem),新PropertyMetadata(的String.Empty));
    #区域INotifyPropertyChanged的实施
    公共事件PropertyChangedEventHandler的PropertyChanged;    公共无效RaisePropertyChanged([CallerMemberNameAttribute]字符串参数propertyName =)
    {
        如果(的PropertyChanged!= NULL)
            的PropertyChanged(这一点,新PropertyChangedEventArgs(propertyName的));
    }
    #endregion
}
公共类InfoTable:ItemsControl的
{    公共枚举ColumnSizeModes
    {
        AutoFitGrowLast,//收缩以适应,除了它扩展填补父最后一列。
        UniformWidth,//所有列的宽度都相同。表扩展以填充母
        自动调整//收缩以适应。表不扩张,以填补父
    }
    公共ColumnSizeModes ColumnSizeMode
    {
        {返回(ColumnSizeModes)的GetValue(ColumnSizeModeProperty); }
        集合{的SetValue(ColumnSizeModeProperty,值); }
    }    公共静态只读的DependencyProperty ColumnSizeModeProperty =
        DependencyProperty.Register(ColumnSizeMode的typeof(ColumnSizeModes)的typeof(InfoTable),新PropertyMetadata(ColumnSizeModes.AutoFitGrowLast));
    大众风格HeaderCellStyle
    {
        {返回(风格)的GetValue(HeaderCellStyleProperty); }
        集合{的SetValue(HeaderCellStyleProperty,值); }
    }    公共静态只读的DependencyProperty HeaderCellStyleProperty =
        DependencyProperty.Register(HeaderCellStyle的typeof(风格)的typeof(InfoTable),新PropertyMetadata(NULL));    大众风格HeaderTextStyle
    {
        {返回(风格)的GetValue(HeaderTextStyleProperty); }
        集合{的SetValue(HeaderTextStyleProperty,值); }
    }    公共静态只读的DependencyProperty HeaderTextStyleProperty =
        DependencyProperty.Register(HeaderTextStyle的typeof(风格)的typeof(InfoTable),新PropertyMetadata(NULL));    大众风格DataCellStyle
    {
        {返回(风格)的GetValue(DataCellStyleProperty); }
        集合{的SetValue(DataCellStyleProperty,值); }
    }    公共静态只读的DependencyProperty DataCellStyleProperty =
        DependencyProperty.Register(DataCellStyle的typeof(风格)的typeof(InfoTable),新PropertyMetadata(NULL));
    大众风格DataTextStyle
    {
        {返回(风格)的GetValue(DataTextStyleProperty); }
        集合{的SetValue(DataTextStyleProperty,值); }
    }    公共静态只读的DependencyProperty DataTextStyleProperty =
        DependencyProperty.Register(DataTextStyle的typeof(风格)的typeof(InfoTable),新PropertyMetadata(NULL));    私人布尔isTemplateApplied;
    私人网格RootGrid;    静态InfoTable()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof运算(InfoTable),新FrameworkPropertyMetadata(typeof运算(InfoTable)));
    }    公共InfoTable()
    {
        装+ = InfoTable_Loaded;
    }    无效InfoTable_Loaded(对象发件人,RoutedEventArgs E)
    {
        如果(!isTemplateApplied)
            返回;        加载 - = InfoTable_Loaded;        RootGrid =(网格)GetTemplateChild(根);        的for(int i = 0; I< Items.Count;我++)
        {
            ColumnDefinition CD =新ColumnDefinition();
            如果(ColumnSizeMode == || ColumnSizeModes.UniformWidth(ColumnSizeMode == ColumnSizeModes.AutoFitGrowLast&放大器;&安培;我== Items.Count - 1))
                cd.Width =新GridLength(1,GridUnitType.Star);
            其他
                cd.Width =新GridLength(1,GridUnitType.Auto);            RootGrid.ColumnDefinitions.Add(CD);
        }        RootGrid.RowDefinitions.Add(新RowDefinition());
        RootGrid.RowDefinitions.Add(新RowDefinition());        的foreach()(在Items.Cast&LT InfoTableItem项目; InfoTableItem&GT)
        {
            INT指数= Items.IndexOf(项目);
            RootGrid.Children.Add(BuildHeaderCell(项指数));
            RootGrid.Children.Add(BuildDataCell(项指数));
        }
    }    公共覆盖无效OnApplyTemplate()
    {        base.OnApplyTemplate();        如果(isTemplateApplied)
            返回;        isTemplateApplied = TRUE;
    }    私人边境BuildHeaderCell(InfoTableItem项目,INT指数)
    {
        边境B =新的边界{样式= HeaderCellStyle};
        TextBlock的T =新的TextBlock {形式= HeaderTextStyle,文本= item.Header};
        b.SetValue(Grid.ColumnProperty,指数);
        b.Child = T;
        返回b;
    }    私人边境BuildDataCell(InfoTableItem项目,INT指数)
    {
        边境B =新的边界{样式= DataCellStyle};
        TextBlock的T =新的TextBlock {风格= DataTextStyle};
        约束力181 =新的Binding {源=项目[指数],路径=新的PropertyPath(数据),UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged};
        t.SetBinding(TextBlock.TextProperty,绑定);
        b.SetValue(Grid.ColumnProperty,指数);
        b.SetValue(Grid.RowProperty,1);
        b.Child = T;
        返回b;
    }}
}

Generic.xaml

 < ResourceDictionary中
    的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
    的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
    XMLNS:地方=CLR的命名空间:InfoTableHost>
    <风格的TargetType ={X:类型本地:InfoTable}>
        < setter属性=了borderThicknessVALUE =0/>
        < setter属性=保证金VALUE =0/>
        < setter属性=填充VALUE =0/>
        < setter属性=VerticalAlignmentVALUE =顶部/>
        < setter属性=HeaderCellStyle>
            < Setter.Value>
                <风格的TargetType =边框>
                    < setter属性=保证金VALUE =0/>
                    < setter属性=填充VALUE =4/>
                    < setter属性=背景值=灰色/>
                    < setter属性=BorderBrushVALUE =黑/>
                    <5,5,5,0.5二传手属性=了borderThickness值= />
                < /样式和GT;
            < /Setter.Value>
        < /二传手>
        < setter属性=HeaderTextStyle>
            < Setter.Value>
                <风格的TargetType =TextBlock的>
                    < setter属性=前景VALUE =白/>
                < /样式和GT;
            < /Setter.Value>
        < /二传手>        < setter属性=DataCellStyle>
            < Setter.Value>
                <风格的TargetType =边框>
                    < setter属性=保证金VALUE =0/>
                    < setter属性=填充VALUE =4/>
                    < setter属性=背景VALUE =深灰/>
                    < setter属性=BorderBrushVALUE =黑/>
                    <5,0,5,0.5二传手属性=了borderThickness值= />
                < /样式和GT;
            < /Setter.Value>
        < /二传手>        < setter属性=DataTextStyle>
            < Setter.Value>
                <风格的TargetType =TextBlock的>
                    < setter属性=前景VALUE =白/>
                < /样式和GT;
            < /Setter.Value>
        < /二传手>        < setter属性=模板>
            < Setter.Value>
                <的ControlTemplate的TargetType ={X:类型本地:InfoTable}>
                    <边框背景={TemplateBinding背景}
                            BorderBrush ={TemplateBinding BorderBrush}
                            了borderThickness ={TemplateBinding了borderThickness}
                            填充={TemplateBinding填充}
                            VerticalAlignment ={TemplateBinding VerticalAlignment}>                        <电网VerticalAlignment =评出的X:NAME =根保证金=0>                        < /网格和GT;
                    < /边框>
                < /控件模板>
            < /Setter.Value>
        < /二传手>
    < /样式和GT;
< / ResourceDictionary的>

MainWindow.xaml(主机页)

 <窗​​口x:类=InfoTableHost.MainWindow
        的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
        的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
        XMLNS:地方=CLR的命名空间:InfoTableHost
        标题=主窗口HEIGHT =350WIDTH =525填充=0>
    <的StackPanel的DataContext ={结合观察}>
        < StackPanel.Resources>
            <风格的TargetType =TextBlock的>
                < setter属性=字号VALUE =18/>
                < setter属性=前景VALUE =黑/>
            < /样式和GT;
        < /StackPanel.Resources>
        <局部:InfoTable>
            <局部:InfoTableItem标题=未绑定头数据=绑定数据/>
            <局部:InfoTableItem标题=观察日数据={结合ObSDate}/>
            <局部:InfoTableItem标题=关闭数据={结合}关闭/>
        < /地方:InfoTable>
        <的TextBlock>这TextBlock的绑定工作:其中,TextBlock的文本={结合ObsDate}/>< / TextBlock的>
    < / StackPanel的>
< /窗GT;

MainWindow.xaml.cs

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls的;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.ComponentModel;
使用System.Runtime.CompilerServices;命名空间InfoTableHost
{
    ///<总结>
    ///为MainWindow.xaml交互逻辑
    ///< /总结>
    公共部分类主窗口:窗口
    {
        市民观察观察{搞定;组; }        公共主窗口()
        {            的InitializeComponent();
            的DataContext =这一点;
            观察=新观察{ObsDate = DateTime.Now,关闭=2201.55米};
        }
    }    公共类观察:INotifyPropertyChanged的
    {
        私人的DateTime _ObsDate;
        公众的DateTime ObsDate
        {
            {返回_ObsDate; }
            组
            {
                如果(_ObsDate!=值)
                {
                    _ObsDate =价值;
                    RaisePropertyChanged();
                }
            }
        }
        私人小数_close;
        公共小数关闭
        {
            {返回_close; }
            组
            {
                如果(_close!=值)
                {
                    _close =价值;
                    RaisePropertyChanged();
                }
            }
        }
        #区域INotifyPropertyChanged的实施
        公共事件PropertyChangedEventHandler的PropertyChanged;        公共无效RaisePropertyChanged([CallerMemberNameAttribute]字符串参数propertyName =)
        {
            如果(的PropertyChanged!= NULL)
                的PropertyChanged(这一点,新PropertyChangedEventArgs(propertyName的));
        }
        #endregion
    }}


解决方案

原来,问题出在InfoTableItem类。显然的DependencyObject不继承父控件的DataContext的这样的结合没有DataContext的。要解决这个问题,使InfoTableItem自FrameworkElement继承和你做生意:

 公共类InfoTableItem:FrameworkElement的
{
   ...
}

The code below is a mostly working control that can be used to display an object in a table with two rows. The first row is the header row and the second row displays the data. Properties of the object being displayed can be defined as the Items for the control. Each item is displayed as a column in the generated table. I do not want to use reflection to implement this control. This question is not about reflection.

The control has two problems:

1.) It is not written in "WPF form" (for lack of a better description) because I create objects in code rather than let the binding engine do the work. The reason I have it coded the way do is because I don't know how to code it correctly. Note I am using a grid for (what should be) the ItemsPanel for the control. I want to use a grid because I want the output to be in table form with borders. For every Item in the Items control I need to bind to two TextBlocks in the the first and second rows of the grid. I also need to add columns so each Item in the Items property shows up in a new column.

2.) The bindings created in the BuildDataCell method don't work. This problem will most likely be resolved if 1.) is resolved. In the unlikely event the control cannot be written in WPF form I would like to use it as-is if I can make the bindings work.

The article below shows up in several StackOverflow questions that I came across while researching this. It either does not answer my question or answers it but I don't know why. http://drwpf.com/blog/2009/05/12/itemscontrol-l-is-for-lookless/#TemplatingAnItemsControl This article is also relevant but I cannot apply it to this problem: http://blog.scottlogic.com/2010/11/15/using-a-grid-as-the-panel-for-an-itemscontrol.html

InfoTable.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace InfoTableHost
{
public class InfoTableItem : DependencyObject
{
    public String Header
    {
        get { return (String)GetValue(HeaderProperty); }
        set { SetValue(HeaderProperty, value); }
    }

    public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("Header", typeof(String), typeof(InfoTableItem), new PropertyMetadata(String.Empty));



    public string Data
    {
        get { return (string)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(string), typeof(InfoTableItem), new PropertyMetadata(String.Empty));


    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged([CallerMemberNameAttribute] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}


public class InfoTable : ItemsControl
{

    public enum ColumnSizeModes
    {
        AutoFitGrowLast,         // Shrink to fit except last column which expands to fill parent.
        UniformWidth,           // All Columns are the same width.  Table expands to fill parent
        AutoFit                // Shrink to fit.  Table does not expand to fill parent    
    }


    public ColumnSizeModes ColumnSizeMode
    {
        get { return (ColumnSizeModes)GetValue(ColumnSizeModeProperty); }
        set { SetValue(ColumnSizeModeProperty, value); }
    }

    public static readonly DependencyProperty ColumnSizeModeProperty =
        DependencyProperty.Register("ColumnSizeMode", typeof(ColumnSizeModes), typeof(InfoTable), new PropertyMetadata(ColumnSizeModes.AutoFitGrowLast));




    public Style HeaderCellStyle
    {
        get { return (Style)GetValue(HeaderCellStyleProperty); }
        set { SetValue(HeaderCellStyleProperty, value); }
    }

    public static readonly DependencyProperty HeaderCellStyleProperty =
        DependencyProperty.Register("HeaderCellStyle", typeof(Style), typeof(InfoTable), new PropertyMetadata(null));



    public Style HeaderTextStyle
    {
        get { return (Style)GetValue(HeaderTextStyleProperty); }
        set { SetValue(HeaderTextStyleProperty, value); }
    }

    public static readonly DependencyProperty HeaderTextStyleProperty =
        DependencyProperty.Register("HeaderTextStyle", typeof(Style), typeof(InfoTable), new PropertyMetadata(null));



    public Style DataCellStyle
    {
        get { return (Style)GetValue(DataCellStyleProperty); }
        set { SetValue(DataCellStyleProperty, value); }
    }

    public static readonly DependencyProperty DataCellStyleProperty =
        DependencyProperty.Register("DataCellStyle", typeof(Style), typeof(InfoTable), new PropertyMetadata(null));


    public Style DataTextStyle
    {
        get { return (Style)GetValue(DataTextStyleProperty); }
        set { SetValue(DataTextStyleProperty, value); }
    }

    public static readonly DependencyProperty DataTextStyleProperty =
        DependencyProperty.Register("DataTextStyle", typeof(Style), typeof(InfoTable), new PropertyMetadata(null));

    private bool isTemplateApplied;
    private Grid RootGrid;

    static InfoTable()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(InfoTable), new FrameworkPropertyMetadata(typeof(InfoTable)));
    }

    public InfoTable()
    {
        Loaded += InfoTable_Loaded;
    }

    void InfoTable_Loaded(object sender, RoutedEventArgs e)
    {
        if (!isTemplateApplied)
            return;

        Loaded -= InfoTable_Loaded;

        RootGrid = (Grid)GetTemplateChild("root");

        for (int i = 0; i < Items.Count; i++)
        {
            ColumnDefinition cd = new ColumnDefinition();
            if (ColumnSizeMode == ColumnSizeModes.UniformWidth || (ColumnSizeMode == ColumnSizeModes.AutoFitGrowLast && i == Items.Count - 1))
                cd.Width = new GridLength(1, GridUnitType.Star);
            else
                cd.Width = new GridLength(1, GridUnitType.Auto);

            RootGrid.ColumnDefinitions.Add(cd);
        }

        RootGrid.RowDefinitions.Add(new RowDefinition());
        RootGrid.RowDefinitions.Add(new RowDefinition());

        foreach (InfoTableItem item in Items.Cast<InfoTableItem>())
        {
            int index = Items.IndexOf(item);
            RootGrid.Children.Add(BuildHeaderCell(item, index));
            RootGrid.Children.Add(BuildDataCell(item, index));
        }
    }

    public override void OnApplyTemplate()
    {

        base.OnApplyTemplate();

        if (isTemplateApplied)
            return;

        isTemplateApplied = true;
    }

    private Border BuildHeaderCell(InfoTableItem item, int index)
    {
        Border b = new Border { Style = HeaderCellStyle };
        TextBlock t = new TextBlock { Style = HeaderTextStyle, Text = item.Header };
        b.SetValue(Grid.ColumnProperty, index);
        b.Child = t;
        return b;
    }

    private Border BuildDataCell(InfoTableItem item, int index)
    {
        Border b = new Border { Style = DataCellStyle };
        TextBlock t = new TextBlock { Style = DataTextStyle };
        Binding binding = new Binding { Source = Items[index], Path = new PropertyPath("Data"), UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
        t.SetBinding(TextBlock.TextProperty, binding);
        b.SetValue(Grid.ColumnProperty, index);
        b.SetValue(Grid.RowProperty, 1);
        b.Child = t;
        return b;
    }

}
}

Generic.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:InfoTableHost">


    <Style TargetType="{x:Type local:InfoTable}">
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Margin" Value="0"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="VerticalAlignment" Value="Top"/>
        <Setter Property="HeaderCellStyle">
            <Setter.Value>
                <Style TargetType="Border">
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="4" />
                    <Setter Property="Background" Value="Gray"/>
                    <Setter Property="BorderBrush" Value="Black"/>
                    <Setter Property="BorderThickness" Value=".5,.5,.5,.5"/>
                </Style>
            </Setter.Value>
        </Setter>
        <Setter Property="HeaderTextStyle">
            <Setter.Value>
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="White"/>
                </Style>
            </Setter.Value>
        </Setter>

        <Setter Property="DataCellStyle">
            <Setter.Value>
                <Style TargetType="Border">
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="4" />
                    <Setter Property="Background" Value="DarkGray"/>
                    <Setter Property="BorderBrush" Value="Black"/>
                    <Setter Property="BorderThickness" Value=".5,0,.5,.5"/>
                </Style>
            </Setter.Value>
        </Setter>

        <Setter Property="DataTextStyle">
            <Setter.Value>
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="White"/>
                </Style>
            </Setter.Value>
        </Setter>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:InfoTable}">
                    <Border Background="{TemplateBinding Background}" 
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            VerticalAlignment="{TemplateBinding VerticalAlignment}">

                        <Grid VerticalAlignment="Top" x:Name="root" Margin="0">

                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

MainWindow.xaml (Host page)

<Window x:Class="InfoTableHost.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:InfoTableHost"
        Title="MainWindow" Height="350" Width="525" Padding="0">
    <StackPanel DataContext="{Binding Observation}" >
        <StackPanel.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="FontSize" Value="18"/>
                <Setter Property="Foreground" Value="Black"/>
            </Style>
        </StackPanel.Resources>
        <local:InfoTable>
            <local:InfoTableItem Header="Unbound Header" Data="Unbound Data"/>
            <local:InfoTableItem Header="Observation Date" Data="{Binding ObSDate}"/>
            <local:InfoTableItem Header="Close" Data="{Binding Close}"/>
        </local:InfoTable>
        <TextBlock>This TextBlock Binding Works: <TextBlock Text="{Binding ObsDate}" /></TextBlock>
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace InfoTableHost
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public Observation Observation { get; set; }

        public MainWindow()
        {

            InitializeComponent();
            DataContext = this;
            Observation = new Observation { ObsDate = DateTime.Now, Close = 2201.55m };
        }
    }

    public class Observation : INotifyPropertyChanged
    {
        private DateTime _ObsDate;
        public DateTime ObsDate 
        {
            get { return _ObsDate; }
            set
            {
                if (_ObsDate != value)
                {
                    _ObsDate = value;
                    RaisePropertyChanged();
                }
            }
        }


        private decimal _Close;
        public decimal Close
        {
            get { return _Close; }
            set
            {
                if (_Close != value)
                {
                    _Close = value;
                    RaisePropertyChanged();
                }
            }
        }


        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged([CallerMemberNameAttribute] string propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion


    }

}

解决方案

It turns out that the problem is with the InfoTableItem class. Apparently DependencyObject does not inherit the DataContext of the parent control so the binding has no DataContext. To resolve this, make InfoTableItem inherit from FrameworkElement and you are in business:

public class InfoTableItem : FrameworkElement
{
   ...
}

这篇关于我怎样写这个的ItemsControl所以WPF将使用绑定生成输出网格列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆