2016-10-04 3 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

관련 문제