【问题标题】:Is it possible to bind 2 properties into a single DataGrid field?是否可以将 2 个属性绑定到单个 DataGrid 字段中?
【发布时间】:2012-06-07 15:05:03
【问题描述】:

目前我有以下内容:

<DataGridTextColumn Header="Customer Name" 
    x:Name="columnCustomerSurname" 
    Binding="{Binding Path=Customer.FullName}" SortMemberPath="Customer.Surname"
    IsReadOnly="True">
</DataGridTextColumn>

其中Customer.FullName 定义为:

public string FullName
{
    get { return string.Format("{0} {1}", this.Forename, this.Surname); }
}

绑定有效,但并不理想。

如果有人更新 ForenameSurname 属性,则更新不会反映在 DataGrid 中,直到它被刷新。

我发现了类似的问题,例如https://stackoverflow.com/a/5407354/181771 使用 MultiBinding 但这适用于 TextBlock 而不是 DataGrid

我还有其他方法可以让它工作吗?

【问题讨论】:

    标签: c# wpf xaml binding


    【解决方案1】:

    一种选择是基于两个文本块创建一个复合模板列,当对任一属性进行更改时仍允许表单更新。

    例如。

    <DataGridTemplateColumn Header="Customer Name">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Customer.ForeName}"/>
                    <TextBlock Text="{Binding Path=Customer.SurName}"/>
                </StackPanel>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    【讨论】:

      【解决方案2】:

      您应该从ForenameSurname 发出FullName 的属性更改通知,例如

      public string Forename
      {
          get{ return _forename; }
          set
          {
              if(value != _forename)
              {
                  _forename = value;
                  RaisePropertyChanged("Forename");
                  RaisePropertyChanged("Fullname");
              }
          }
      }
      

      或者,你像这样缓存 FullName 的生成值

      public string Forename
      {
          get{ return _forename; }
          set
          {
              if(value != _forename)
              {
                  _forename = value;
                  RaisePropertyChanged("Forename");
                  UpdateFullName();
              }
          }
      }
      
      private void UpdateFullName()
      {  
          FullName = string.Format("{0} {1}", this.Forename, this.Surname); 
      }
      
      public string FullName
      {
          get{ return _fullname; }
          private set
          {
              if(value != _fullname)
              {
                  _fullname = value;
                  RaisePropertyChanged("FullName");
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-18
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-30
        • 2013-11-16
        • 2011-04-01
        • 2011-03-21
        相关资源
        最近更新 更多