如何在DataGridTextColumn上使用MultiBinding?

时间:2015-10-20 12:26:02

标签: c# wpf xaml data-binding

我的Height对象上有WidthImageDimension两个属性,我想将它们绑定在一起,所以显示的内容类似于50x60(中间是x个字符)?我怎样才能做到这一点?下面的代码给我一个错误说

  

“对象引用未设置为对象实例。”

<cst:CustomDataGrid x:Name="grdImageDimension"  
                    ItemsSource="{Binding ImageDimensions, IsAsync=True}"  
   <DataGridTextColumn Header="ImageDimension" Width="50">
      <DataGridTextColumn.Binding>
         <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="ImageDimensions.Height" />
            <Binding Path="ImageDimensions.Width" />                              
         </MultiBinding>
      </DataGridTextColumn.Binding>
   </DataGridTextColumn>
</cst:CustomDataGrid>

视图模型:

Public Class ImageDimensionsVM

    Private m_ImageDimensions As ObservableCollection(Of ImageDimension)
    Public Property ImageDimensions() As ObservableCollection(Of ImageDimension)
        Get
            Return m_ImageDimensions
        End Get
        Set(value As ObservableCollection(Of ImageDimension))
            m_ImageDimensions = value
        End Set
    End Property

1 个答案:

答案 0 :(得分:8)

如果你想将数据绑定到ImageDimension对象的属性,只需直接使用它们@Giangregorio指出:

<Window x:Class="DataGridTextHeightWidth.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
   <Grid>
      <DataGrid x:Name="grdImageDimension" ItemsSource="{Binding 
                ImageDimensions, IsAsync=True}" AutoGenerateColumns="False">
         <DataGrid.Columns>
            <DataGridTextColumn x:Name="MyGridColumn"
                                Header="ImageDimension"
                                Width="*">
               <DataGridTextColumn.Binding>
                  <MultiBinding StringFormat="{}{0} x {1}">
                     <Binding Path="Height" />
                     <Binding Path="Width" />
                  </MultiBinding>
               </DataGridTextColumn.Binding>
            </DataGridTextColumn>
         </DataGrid.Columns>
      </DataGrid>
   </Grid>
</Window>

代码背后:

public partial class MainWindow : Window
{
   public MainWindow()
   {
      InitializeComponent(); 

      // Create list
      MyImageDimensionCol col = new MyImageDimensionCol();
      col.ImageDimensions = new ObservableCollection<ImageDimension>();
      col.ImageDimensions.Add(new ImageDimension() { Height = 5, Width = 10 });
      col.ImageDimensions.Add(new ImageDimension() { Height = 15, Width = 20 });
      col.ImageDimensions.Add(new ImageDimension() { Height = 5, Width = 5 });
      DataContext = col;
   }
}

public class MyImageDimensionCol
{
   public ObservableCollection<ImageDimension> ImageDimensions { get; set; }
}

public class ImageDimension
{
   public int Height { get; set; }
   public int Width { get; set; }
}