绑定到dataGrid SelectedItem

时间:2014-05-20 08:18:57

标签: c# wpf datagrid

我有这样的DataGrid:

<DataGrid AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" GridLinesVisibility="None">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border BorderThickness="{Binding ???}" BorderBrush="Black" >
                        <Grid></Grid>
                    </Border>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid>

我需要将CellTemplate中Border的BorderThickness绑定到DataGrid.SelectedItem。例如:如果单元格处于选定行,则厚度必须为1,1,1,1否则为零。 (我知道转换器)。怎么做?

2 个答案:

答案 0 :(得分:1)

可以使用触发器实现:

  <DataGrid AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" GridLinesVisibility="None">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Border  BorderBrush="Black" >
                            <Border.Style>
                                <Style TargetType="Border">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell}}" Value="True">
                                            <Setter Property="BorderThickness" Value="1"></Setter>
                                        </DataTrigger>
                                    </Style.Triggers>

                                </Style>
                            </Border.Style>
                            <Grid></Grid>
                        </Border>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
         </DataGrid.Columns>
    </DataGrid>

直接设置CellStyle,如

       <DataGrid AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" GridLinesVisibility="None">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="BorderThickness" Value="1"></Setter>
                                <Setter Property="BorderBrush" Value="Black"></Setter>
                            </Trigger>
                        </Style.Triggers>

                    </Style>

答案 1 :(得分:0)

转换器可能不是这样的方法,尝试在所选网格项上使用更改边框样式的数据触发器,在此http://www.wpf-tutorial.com/styles/trigger-datatrigger-event-trigger/