2011-09-15 15 views
3

我有一個WPF的DataGrid,我想文字環繞適用於所有的細胞,所以我定義了這種風格:DataGrid的數據綁定問題與樣式

 <DataGrid.CellStyle> 
      <Style TargetType="DataGridCell"> 
       <Setter Property="ContentTemplate"> 
        <Setter.Value> 
         <DataTemplate> 
          <TextBlock TextWrapping="Wrap" FontSize="15" Text="{Binding}" VerticalAlignment="Center" 
           HorizontalAlignment="Center" ></TextBlock> 
         </DataTemplate> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </DataGrid.CellStyle> 
     <DataGrid.Columns> 

      <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="95" /> 
      <DataGridTextColumn Header="Address" Binding="{Binding Address}" Width="95" /> 
      <DataGridTextColumn Header="Category" Binding="{Binding Category}" Width="95" /> 

     </DataGrid.Columns> 

,並設置我的DataGrid的ItemsSource時在我的代碼背後是這樣的:

 myDataGrid.ItemsSource= new Customers[] 
     { 
       new ComputerStandard{Name="Michael Thomas",Address="16 Greenville Avenue",Category="A"},    
       new ComputerStandard{Name="Fiona Thompson",Address="19 Wright Street",Category="F"},    
       new ComputerStandard{Name="Jack Smith",Address="133 Kensington Road",Category="B"}, 
       new ComputerStandard{Name="Michael jackson",Address="11 Wine Street",Category="C"}, 
       new ComputerStandard{Name="Jerry Holmes",Address="10 Awson Street",Category="G"}, 
       new ComputerStandard{Name="David Philips",Address="Not Specified",Category="A"} 
     }; 

但一些地方失敗,我在我的風格Text="{Binding}"設置我的綁定表達式和我結束了:

enter image description here

很顯然,綁定表達式Text="{Binding}"失敗了,我知道這是因爲當我刪除樣式時,一切都很完美。我該如何解決這個問題?

在此先感謝。

回答

2

設置DataGridColumn.Binding屬性不會爲每個DataGridCell設置DataContext。該DataContext仍然等於整行的DataContext

從綁定ContentTemplate,有約束力的Template開關,然後你可以訪問ContentPresenter

<Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="DataGridCell"> 
      <TextBlock TextWrapping="Wrap" FontSize="15" 
         VerticalAlignment="Center" HorizontalAlignment="Center"> 

       <ContentPresenter Content="{TemplateBinding Content}" /> 

      </TextBlock> 
     </ControlTemplate> 
    </Setter.Value> 
</Setter> 
1

這將幫助:

<Style x:Key="MyGrid" TargetType="{x:Type DataGridCell}">  
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type DataGridCell}"> 
       <Border x:Name="MyBorder" > 
        <TextBlock Background="Transparent" TextWrapping="WrapWithOverflow" 
        TextTrimming="CharacterEllipsis" Height="auto" Width="auto"> 
        <ContentPresenter 
        Content="{TemplateBinding Property=ContentControl.Content}" 
        ContentTemplate="{TemplateBinding Property=ContentControl.Content}"/> 
        </TextBlock> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

here服用。