如何在 WPF 中绑定用户控件作为 DataGridTemplateColumn 失败

2024-04-29

我想使用来自不同程序集的用户控件作为 DataGridTemplateColumn。 我已经看过很多例子和问题,比如this https://stackoverflow.com/questions/13956767/binding-to-custom-dependency-property-again, this https://stackoverflow.com/questions/5698865/simple-dependency-property-and-usercontrol-issues-in-c-sharp, this https://stackoverflow.com/questions/16694327/how-to-binding-a-itemscontrol-itemssource-with-a-property-of-the-window-in-wpf and this http://zamjad.wordpress.com/2009/12/30/using-user-control-in-data-grid/。我不明白为什么我的代码不起作用。 这里是:

主窗口.xaml

<Window x:Class="WpfTemplatesDemo3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:extraUserControl="clr-namespace:Templates;assembly=Templates"
    xmlns:wpfTemplatesDemo3="clr-namespace:WpfTemplatesDemo3"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid x:Name="TableDataGrid" DataContext="{Binding   UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}" Width="*"/>
            <DataGridTextColumn Binding="{Binding Age}" Width="*"/> 
            <DataGridTextColumn Binding="{Binding Description}" Width="2*"/>
            <DataGridTemplateColumn  Width="3*" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <extraUserControl:BirthDateControl BirthDayObj="{Binding BirthDay, ElementName=TableDataGrid}"   />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
</Window>

MainWindow.xaml.cs

namespace WpfTemplatesDemo3
{
  public partial class MainWindow : Window
  {
    public ObservableCollection<Person> Persons { get;set; }

    public MainWindow()
    {
      InitializeComponent();
      this.populatePersons();
      this.TableDataGrid.ItemsSource = this.Persons;
    }

    private void populatePersons()
    {
      this.Persons = new ObservableCollection<Person>();
      Persons.Add(new Person { Age = 10, Name = "John0", BirthDay = new BirthDate(1, 2, 3) });
      Persons.Add(new Person { Age = 11, Name = "John1", BirthDay = new BirthDate(2, 3, 4) });
      Persons.Add(new Person { Age = 12, Name = "John2", BirthDay = new BirthDate(3, 4, 5) });
      Persons.Add(new Person { Age = 13, Name = "John3", BirthDay = new BirthDate(4, 5, 6) });
      Persons.Add(new Person { Age = 14, Name = "John4", BirthDay = new BirthDate(5, 6, 7) });
      Persons.Add(new Person { Age = 15, Name = "John5", BirthDay = new BirthDate(6, 7, 8) });
    }
  }
}

出生日期控件.xaml

<UserControl x:Class="Templates.BirthDateControl"
             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:DesignWidth="300" Height="52.273"
             DataContext="{Binding RelativeSource={RelativeSource Self}}"
             >
    <Grid>
        <StackPanel>
        <Label Content="Date:"/>
            <StackPanel Orientation="Horizontal" >
                <TextBox Text="{Binding BirthDayObj.Day}" />
                <TextBox Text="{Binding BirthDayObj.Month}"/>
                <TextBox Text="{Binding BirthDayObj.Year}" />
            </StackPanel>
        </StackPanel>
    </Grid>
</UserControl>

出生日期控件.xaml.cs

namespace Templates
{
  public partial class BirthDateControl : System.Windows.Controls.UserControl
  {
    public static DependencyProperty BirthDayObjProperty =
      DependencyProperty.Register("BirthDayObj", typeof(BirthDate), typeof(BirthDateControl));

    public BirthDate BirthDayObj
    {
      get
      {
        return ((BirthDate)GetValue(BirthDayObjProperty));
      }
      set
      {
        SetValue(BirthDayObjProperty, value);
      }
    }

    public BirthDateControl()
    {
      InitializeComponent();
    }
  }
}

人物.cs

namespace Entities
{
  public class Person : INotifyPropertyChanged
  {
    private string name;
    private int age;
    private BirthDate _birthDay;

    public string Name
    {
      get { return this.name; }
      set { 
        this.name = value;
        this.OnPropertyChanged("Name");
        this.OnPropertyChanged("Description");
      }
    }

    public int Age
    {
      get { return this.age; }
      set
      {
        this.age = value;
        this.OnPropertyChanged("Age");
        this.OnPropertyChanged("Description");
      }
    }

      public string Description
      {
        get { return Name + "_" + Age + "_" + BirthDay.Day; }
      }


    public BirthDate BirthDay
    {
      get { return this._birthDay; }
      set
      {
        this._birthDay = value;
        this.OnPropertyChanged("BirthDate");
        this.OnPropertyChanged("Description");
      }
    }


      public event PropertyChangedEventHandler PropertyChanged;

      protected void OnPropertyChanged(string propName)
      {
        if (this.PropertyChanged != null)
          this.PropertyChanged(
              this, new PropertyChangedEventArgs(propName));
      }
    }
}

出生日期.cs

namespace Entities
{
  public class BirthDate : INotifyPropertyChanged
  {
    private int day;
    private int month;
    private int year;

    public BirthDate(int day, int month, int year)
    {
      this.day = day;
      this.month = month;
      this.year = year;
    }

    public int Day {
      get { return this.day; }
      set
      {
        this.day = value;
        this.OnPropertyChanged("day");
      }
    }

    public int Month {
      get { return this.month; }
      set
      {
        this.month = value;
        this.OnPropertyChanged("month");
      }
    }

    public int Year {
      get { return this.year; }
      set
      {
        this.year = value;
        this.OnPropertyChanged("year");
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propName)
    {
      if (this.PropertyChanged != null)
        this.PropertyChanged(
            this, new PropertyChangedEventArgs(propName));
    }
  }
}

如果我运行它,它将显示列,但生日列为空。

没有错误或警告,但这显示在输出中:

System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
'WpfTemplatesDemo3.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\UIAutomationTypes\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationTypes.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Windows.Data Error: 40 : BindingExpression path error: 'BirthDay' property not found on 'object' ''DataGrid' (Name='TableDataGrid')'. BindingExpression:Path=BirthDay; DataItem='DataGrid' (Name='TableDataGrid'); target element is 'BirthDateControl' (Name=''); target property is 'BirthDayObj' (type 'BirthDate')
The program '[16364] WpfTemplatesDemo3.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

我不明白为什么它不将数据绑定到用户控件。


The DataGridRowDataContext of Person目的。这DataContext是在你们之间遗传的VisualTree,因此您的 UC 具有相同的上下文。要使您的示例正常工作:

  1. 丢弃BirthDayObjProperty来自你的加州大学。
  2. 把这条线从你的DataGrid: DataContext="{Binding UpdateSourceTrigger=PropertyChanged}"
  3. 在你的 UC 中扔掉这一行:DataContext="{Binding RelativeSource={RelativeSource Self}}"
  4. 您的 UC 绑定可以非常简单:

    <Grid>
        <StackPanel>
            <Label Content="Date:"/>
            <StackPanel Orientation="Horizontal" >
                <TextBox Text="{Binding BirthDay.Day}" />
                <TextBox Text="{Binding BirthDay.Month}"/>
                <TextBox Text="{Binding BirthDay.Year}" />
            </StackPanel>
        </StackPanel>
    </Grid>
    
  5. 阅读更多关于DataContext一般而言,继承和绑定, 因为你显然滥用了它们。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WPF 中绑定用户控件作为 DataGridTemplateColumn 失败 的相关文章

随机推荐