2016-10-04 59 views
1

比方說,我有一個DataGrid綁定到對象的集合。這些對象具有屬性PropertyAPropertyB。我想要第一列顯示PropertyA,但是當我選擇一行時,我希望所選行僅顯示PropertyB。我怎樣才能做到這一點?如何更改所選項目的DataGridColumn綁定?

目的

public class MyObject 
{ 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
} 

的XAML

<DataGrid ItemsSource="{Binding Path=MyObjects}"> 
    <DataGrid.Columns> 
    <DataGridTextColumn Header="Foo" Binding="{Binding Path=PropertyA}" /> 
    </DataGrid.Columns> 
</DataGrid> 

這將顯示在數據網格中的每一行中PropertyA的值。但是,當我選擇一行時,我只希望該行更改爲顯示PropertyB。

回答

1

試試這個:

XAML:

Window x:Class="WpfApplication296.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication296" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="300" Width="300"> 

    <Window.Resources> 

     <DataTemplate x:Key="TemplateA"> 
      <TextBlock Text="{Binding PropertyA}" FontSize="24" /> 
     </DataTemplate> 

     <DataTemplate x:Key="TemplateB"> 
      <TextBlock Text="{Binding PropertyB}" FontSize="24"/> 
     </DataTemplate> 

     <Style x:Key="DataGridCellStyle1" 
       TargetType="{x:Type DataGridCell}" 
       BasedOn="{StaticResource {x:Type DataGridCell}}"> 
      <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}"/> 
      <Style.Triggers> 
       <Trigger Property="IsSelected" Value="True"> 
        <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}"/> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 

    </Window.Resources> 

    <Window.DataContext> 
     <local:MyViewModel/> 
    </Window.DataContext> 

    <Grid> 

     <DataGrid ItemsSource="{Binding MyObjects}" 
        AutoGenerateColumns="False"> 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Foo" 
            Width="*" 
            Binding="{Binding PropertyA}" 
            CellStyle="{StaticResource DataGridCellStyle1}" /> 
      </DataGrid.Columns> 
     </DataGrid> 

    </Grid> 
</Window> 

視圖模型:

public class MyViewModel 
{ 
    public ObservableCollection<MyObject> MyObjects { get; set; } 

    public MyViewModel() 
    { 
     MyObjects = new ObservableCollection<MyObject> 
     { 
      new MyObject {PropertyA = " AAA 101", PropertyB=" BBBBBB 001" }, 
      new MyObject {PropertyA = " AAA 102", PropertyB=" BBBBBB 002" }, 
      new MyObject {PropertyA = " AAA 103", PropertyB=" BBBBBB 003" }, 
      new MyObject {PropertyA = " AAA 104", PropertyB=" BBBBBB 004" }, 
      new MyObject {PropertyA = " AAA 105", PropertyB=" BBBBBB 005" }, 
     }; 
    } 
} 

enter image description here

相關問題